【发布时间】: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 == 0和col == 0条件都为真,然后您退出函数。你不是打算从迷宫的边缘开始吗? -
@MattBurland 我只是通过这可能是起点,起点的参数是什么?
-
@Milas:我不知道,由你决定你的程序应该如何工作。大多数迷宫都有一个入口点和一个出口点。正如你所拥有的,边缘上的任何一点都是出口点。
标签: c# algorithm graph-algorithm