程序设计与数据结构有关递归的学习:迷宫项目
学习《程序设计与数据结构》中的11章递归,其中有段关于迷宫设计的代码。它通过设计一个二元数组,并在其中随机分布0和1,1为通路,0则不能通过。当程序开始运行的时候,它会首先把试探的路以1变3的方式来体验,当最后得到出去的路的时候,它会将3变成7来显示。
Maze.java
package ch11;
/**
* Created by Funny_One on 2017/9/6.
*/
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, 0, 0},
{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;
if (row == grid.length - 1 && column == grid[0].length - 1) {
done = true;
} else {
done = traverse(row + 1, column);//往下走
if (!done) {
done = traverse(row, column + 1);//往右走
}
if (!done) {
done = traverse(row - 1, column);//往上走
}
if (!done) {
done = traverse(row, column - 1);//往左走
}
}
if (done) {
grid[row][column] = PATH;
}
}
return done;
}
private boolean valid(int row, int column) {
boolean result = false;
if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length ) {
if (grid[row][column] == 1) {
result = true;
}
}
return result;
}
public String toString() {
String result = "\n";
for (int row = 0; row < grid.length; row++) {
for (int column = 0; column < grid[row].length; column++) {
result += grid[row][column] + "";
}
result += "\n";
}
return result;
}
}
MazeSearch.java
package ch11;
/**
* Created by Funny_One on 2017/9/7.
*/
public class MazeSearch {
public static void main (String[] args){
Maze labyrinth = new Maze();
System.out.println(labyrinth);
if(labyrinth.traverse(0,0)){
System.out.println("The maze was successful traversed!");
}else {
System.out.println("There is no possible path.");
}
System.out.println(labyrinth);
}
}
效果:
问题:但当时对递归并不熟悉,因此根本不能理解它以走迷宫的逻辑来走,为什么碰到0之后才会转换为另一个走向。最后经过一步步调试,仔细研究之后,我得到这么一个解释: