【问题标题】:Finding minimal path in maze in C在C中找到迷宫中的最小路径
【发布时间】:2016-12-10 17:31:58
【问题描述】:

所以我需要编写一个代码来找出迷宫中最小路径的长度。

迷宫是一个NxN矩阵,起点是(0,0),终点是(N,N),如果单元格包含1我可以通过它,如果它是0我不能。迷宫可能有解决方案,也可能没有解决方案。

这是我到目前为止的代码,假设它有一个解决方案:

int path_finder(int maze[][N], int n, int row, int col)    // n equal N
{
int i, j, pth;

if (row == n-1 && col == n-1)    // Return 0 if I get to goal
  return 0;

if (col < 0 || row < 0 || row > n-1 || col > n-1)    // Same
  return n*n;

if (maze[row][col] == 0)    // Return big number to make sure it doesn't count
  return n*n;

maze[row][col] = 0;

pth = min( 1+path_finder(maze,n, row+1, col),    // Assume I already know the path
            1+path_finder(maze,n, row-1, col),    // from the next starting point
            1+path_finder(maze,n, row, col+1),    // just add 1 to it
            1+path_finder(maze,n, row, col-1)  );

maze[row][col] = 1;

return pth;
}

我总是得到 N^2+1,我假设它只计算我发送给 min 函数的最后一个参数,但我不知道如何解决它?

【问题讨论】:

  • 你有if (maze[row][col] == 0) 你测试边缘条件,即使它们返回相同的值,在使用前总是检查限制。
  • 注意编译器警告:maze[row][col] == 0; // Make sure... 什么都不做。
  • 将visted 空间标记为墙是个好主意,但是在您递归调用该函数后(在您的min 中),您应该再次将其重置为地板,以便其他解决方案可以探索它。
  • 感谢天气风向标,但是我每次都得到 n^2 作为答案。 M Oehm 如果我重置它,它不会进入无限循环吗?我真的不明白你所说的与根本不将空间标记为墙有什么不同
  • 仅供参考,我之前使用 Dijkstra 算法发布了 maze solution,该算法不需要详尽搜索。该问题还包含指向 duplicate question 的链接,其中包含各种其他迷宫解决方法。

标签: c recursion maze


【解决方案1】:

如果问题切实可行,请使用 A*。

https://github.com/MalcolmMcLean/binaryimagelibrary/blob/master/astar.c

如果问题是人为设计的,因此存在近乎最佳的干扰路径。修改函数取出启发式,进行穷举搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2018-03-24
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多