【问题标题】:Maze algorithm path finder迷宫算法路径查找器
【发布时间】:2014-10-08 12:38:20
【问题描述】:

我试图找到迷宫的路径,下面是代码,它假设进入 recursiveSolve 循环但它继续退出,在第二个 if 条件之后我在这里做错了什么,有人可以帮助我吗? 我将 Washere 和 correctpath 数组默认设置为 false。

recursiveSolve(0, 0);

public static int[,] maze = {{0, 0, 0, 0, 0, 1},
                             {1, 1, 0, 0, 0, 1},
                             {0, 0, 0, 1, 0, 0},
                             {0, 1, 1, 0, 0, 1},
                             {0, 1, 0, 0, 1, 0},
                             {0, 1, 0, 0, 0, 1}};

public static Boolean recursiveSolve(int row, int col) {
    Boolean[,] wasHere = new Boolean[6, 6];
    Boolean[,] correctPath = new Boolean[6, 6]; // The solution to the maze

    if (maze[row, col] == 1 || wasHere[row, col]) {
        return false;
    }
    else if (row == 0 || row == 6 - 1 || col == 0 || col ==6 - 1) {
        correctPath[row, col] = true;
        return true;
    }
    else {
        wasHere[row, col] = true;
        if (recursiveSolve(row - 1, col) || recursiveSolve(row + 1, col) ||
                                            recursiveSolve(row, col - 1) || 
                                            recursiveSolve(row, col +1)) {
            correctPath[row, col] = true;
            return true; // successfully escaped; this square is on path
        }
        else {
            return false;
        }
    }
} 

【问题讨论】:

  • 你试过调试吗?你会看到你的第二个 if 条件为真,导致函数退出。
  • 请注意else if 中的条件:else if (row == 0 || row == 6 - 1 || col == 0 || col ==6 - 1),因为您使用recursiveSolve(0,0) 调用它,row == 0col == 0 条件都为真,然后您退出函数。你不是打算从迷宫的边缘开始吗?
  • @MattBurland 我只是通过这可能是起点,起点的参数是什么?
  • @Milas:我不知道,由你决定你的程序应该如何工作。大多数迷宫都有一个入口点和一个出口点。正如你所拥有的,边缘上的任何一点都是出口点。

标签: c# algorithm graph-algorithm


【解决方案1】:

您的 wasHere 和 correctPath 数组是 recursiveSolve 函数的本地数组,这意味着每次您输入此函数时,数组都会被初始化为 false(或随机值)。

首先尝试将这些数组也设为静态,看看这是否解决了始终为 false 的问题。

此外,您应该从迷宫内部的某个位置开始搜索,而不是从边缘开始搜索(0,0 表示您已经退出了迷宫)。 如果您想从 0,0 开始,请将其标记为起点,并且不要将其作为有效解决方案。

【讨论】:

    【解决方案2】:

    如果您实际上是在进行路径查找,并且这不是需要这种特殊解决方案的练习,那么您可能还想研究 A* 算法,它可能更有效和更健壮。

    Wikipedia

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多