0

一旦它被实例化并且方法 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,所以整个事情不会停止吗?

4

3 回答 3

2

这是你的方法:

public boolean traverse (int row, int column)
{
    boolean done = false;
    if (valid (row, column))
    {
       ...
    }
    return done;
}

因此,如果该点无效,它将跳过所有测试并返回false

于 2012-12-08T03:41:45.523 回答
0

如果有效测试失败,接下来要执行的是“return done”;在方法结束时,将返回 false。这会将有关失败的信息传递回调用者。

于 2012-12-08T03:41:55.737 回答
0

at the first else the row and columns are checked for validity. If the row and columns are not valid the method will not stop instantly, because based on the value of done field the nested if blocks inside the first else will be executed.

于 2012-12-08T03:43:53.437 回答