如何递归搜索矩阵以找到路径

时间:2020-10-01 09:02:34

标签: c++ recursion

我试图递归地移动到grid [] []中的所有坐标,但是我无法正确实现逻辑,有人可以告诉我我在做什么错。 当我在opengl代码中运行程序时,我的程序不断崩溃。我正在尝试可视化opengl中的广度优先搜索路径查找。

您可以在此处找到整个源文件:https://pastebin.com/Jae9f75M

int findPath(Grid* current,int x, int y)
{
    if (!pathFound)
    {
        if (current->isObstacle() || current->isTraversed())
        {
            //do nothing
            std::cout << "obstacle, traversed or start found \n";
        }
        else if (current->isEndPoint())
        {
            pathFound = true;
            std::cout << "end found \n";
        }
        else
        {
            std::cout << "probable path found \n";
            if (x >= 0 && x < GRID_SIZE*2 && y >= 0 && y < GRID_SIZE*2)
            {
                current->setTraversed();

                findPath(grid[x + 1][y], x + 1, y); //right
                findPath(grid[x - 1][y], x - 1, y); //left
                findPath(grid[x][y + 1], x, y + 1); //top
                findPath(grid[x][y - 1], x, y - 1); //bottom
            }
        }
    }
    else
    {
        return 0;
    }
    
}

1 个答案:

答案 0 :(得分:0)

一个主要问题是数据结构的显示方式(一旦您可以清理代码,其他问题也应该摆在您的面前)。而不是原始的Grid*[][](除非确实需要使用,否则不要使用它)以及可以使数据结构适合所需算法的任何东西:

简化的伪代码:

struct GridEntry {
  size_t x;
  size_t y;
  bool operator<(...) {return false;//implement how grid entry should compare}
};

//...

{
   std::vector<GridEntry> my_grid_;

   //.. fill grid whatever
   {
     std::sort(my_grid_.begin(), ...)
     //.. search grid, find path, whatever.
   }
}

如果要查找,请改用map,ala:std::map<GridEntry> my_grid;

相关问题