用递归实现迷宫问题

1.编写迷宫类Maze.java

public class Maze {
  private final int PATH = 7; //PATH用于标记正确路径
  private final int TRIED = 3;//TRIED用于标记能通过且尝试过的路径

  private int[][] grid = {{1, 1, 0, 0},  1, 1, 1, 0}, {0, 1, 0, 0},
		        {0, 1, 1, 1}};  //构造一个迷宫,1表示可通过

  //穿越迷宫的递归方法,返回穿越迷宫成功与否的boolean值
  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;
  }

  //确定坐标能否通过
  public boolean valid(int row, int column) {
    boolean result = false;
    if (row < grid.length && column < grid[0].length) {
      if (grid[row][column] == 1) {
        result = true;
      }
    }
    return result;
  }

  public String toString() {
    String st = "";
    for (int i = 0; i < grid.length; i++) {
      for (int j = 0; j < grid[0].length; j++) {
        st += grid[i][j] + " ";
      }
      st += "\n";
    }
  }
}


2.编写测试类 TestMaze.java

public class TestMaze {
  public static void main(String[] args) {
    Maze maze = new Maze();
    System.out.println("The maze is:\n" + maze.toString());

    if (maze.traverse(0, 0)) {
      System.out.println("The maze has been passed:\n" + maze.toString());
    } else {
      System.out.println("The maze can't be passed!");
    }
  }
}

你可能感兴趣的:(J#)