一旦它被实例化并且方法 traverse(0,0) 被调用,它将自动解决迷宫,显示 7 作为路径,3 作为“尝试过的路径”。我试图理解这段代码,但我被traverse 方法中的第一个 else 语句卡住了。
public class Maze
{
private final int TRIED = 3;
private final int PATH = 7;
private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1,0,0,1},
{0,0,0,0,1,0,1,0,1,0,1,0,0},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1} };
public boolean traverse (int row, int column)
{
boolean done = false;
if (valid (row, column))
{
grid[row][column] = TRIED;
// this cell has been tried
if (row == grid.length-1 && column == grid[0].length-1)
done = true;
// the maze is solved
else
{
done = traverse (row+1, column);
// down
if (!done)
done = traverse (row, column+1);
// right
if (!done)
done = traverse (row-1, column);
// up
if (!done)
done = traverse (row, column-1);
// left
}
if (done)
// this location is part of the final path
grid[row][column] = PATH;
}
return done;
}
//-----------------------------------------------------------------
// Determines if a specific location is valid.
//-----------------------------------------------------------------
private boolean valid (int row, int column)
{
boolean result = false;
// check if cell is in the bounds of the matrix
if (row >= 0 && row < grid.length && column >= 0 &&
column < grid[row].length)
// check if cell is not blocked and not previously tried
if (grid[row][column] == 1)
result = true;
return result;
}
据我所知,
done = traverse (row+1, column);
此行是一个递归调用,会将其向下移动一次,然后再次运行该方法,但如果它无效怎么办?整个方法不停止吗?我不明白在某个点之后控制流转移到哪里是无效的。
例如,如果 [1][0] 无效,控制是否转移回 [0][0] 调用并处理“向右”语句?if (!done) 是什么意思,我的意思是当迷宫完全解决时,done 才等于 true,如果它是有效的,done 将等于 true,所以整个事情不会停止吗?