//Represents a maze of characters.
//The goal is to get from the top left corner to the bottom right, following a path of 1s.
//走1不走0的迷宫的递归实现
public class Maze {
private final int TRIED = 3;
private final int PATH = 7;
//二维数组创建8×13大矩阵作为迷宫
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}};
//Attempts to recursively traverse the maze.
//Inserts special characters indicating locations that have been tried
// and that eventually become part of the solution.
/*基本实际情况有三种:
* 移动操作由于出界而无效
* 移动操作由于以前尝试过而无效
* 移动操作达到最终位置
*/
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 id=s part of the final path
grid[row][column] = PATH;
}
//无路可走返回false
return done;
}
//Determines if a special 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 = 0 && column
关注
打赏
热门博文
- 【Linux】Ubuntu20.04安装和卸载MySQL8
- 【Linux】Ubuntu 20.04 报错 curl: (23) Failure writing output to destination 的解决方法
- 【Java】JUnit 4.13.2 警告 ‘assertEquals(double, double)‘ is deprecated 的解决方法
- 【JavaScript】处理 @parcel/transformer-js: Browser scripts cannot have imports or exports.
- 【Python】处理TypeError: Plain typing.NoReturn is not valid as type argument
- 【Python】Matplotlib可视化50例
- 【C语言】C语言修改MySQL数据库
- 【Java】从默认包导入类和对象报错的解决方法
- 【Java】panel.getGraphics()报错空指针异常的解决方法
- 【Java】IDEA编译Java项目报错 java: 找不到符号 的解决方法