Search code examples
c#multidimensional-arrayroboticsa-star

Find closest value in a 2d grid c#


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;

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

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.

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


Solution

  • 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();
    }