在二维网格 c# 中找到最接近的值 [英] Find closest value in a 2d grid c#

查看:27
本文介绍了在二维网格 c# 中找到最接近的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个用于模拟机器人应用程序的 c# 控制台应用程序.我已经为机器人创建了一个 2D 网格来移动:

I have created an c# console application that is used to simulate a robot application. I have created a 2D grid for the robot to move around:

List<List<int> Map;

地图是一个 25x25 的网格(开始时)并填充了以下值:

The map is a 25x25 grid (to start with) and filled with the following values:

0 = Unexplored space,
1 = Explored space,
2 = Wall, 
3 = Obstacle, 
9 = Robot

机器人从位置 (12,12) 开始.我希望能够在此网格中搜索最近的未探索空间并返回该位置,以便我可以将该位置和机器人位置提供给 A* 搜索算法以进行规划.

The robot begins in position (12,12). I would like to be able to search this grid for the nearest Unexplored space and return that position so that I can then feed that position and the robots position to an A* search algorithm for planning.

在 Map 中搜索所述值的最有效方法是什么?

What would be the most efficient method to search through the Map for said value?

谢谢:)

推荐答案

在记事本上写了这个,所以我还没有测试它,但你应该有一个想法.基本上获取所有未探索的地方并按与当前的距离对它们进行排序,然后获取列表中的第一个值.CalculateDistance 方法应该实现 Nikola.Lukovic 提到的公式.

wrote this on a notepad so i havent tested it, but you should get an idea. Basically get all unexplored places and sort them by the distance from current and get the first value in the list. CalculateDistance method should implement the formula Nikola.Lukovic mentioned.

public KeyValuePair<int, int> GetClosestUnexploredPosition(List<List<int>> map, int currentX, int currentY)
{
    Dictionary<KeyValuePair<int, int>, double> unexploredPlaces = new Dictionary<KeyValuePair<int, int>, double>();

    foreach (List<int> valueList in map)
    {
        foreach (int value in valueList)
        {
            if (value == 0)
            {
                int x = map.IndexOf(valueList);
                int y = valueList.IndexOf(value));
                if (x != currentX && y != currentY)
                {
                    unexploredPlaces.Add(new KeyValuePair(x, y), CalculateDistance(currentX, currentY, x, y));
                }
            }
        }
    }

    return unexploredPlaces.OrderBy(x => x.Value).FirstOrDefault();
}

这篇关于在二维网格 c# 中找到最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆