版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013278314/article/details/83823367
首先我们定义一个 n * n 的二维数组,模拟迷宫,用2这个数字表示迷宫的墙壁 ,0表示迷宫的路线 ,那么我们主要的思路就是 在迷宫的入口 判断入口的上下左右 哪一个方向不是墙壁 我们则进入进去,同时我们用1 这个数字表示走过的路线 0表示不通的路线 这就是我们大致的思路 下面是代码实现,代码上面都有具体注释 很容易看懂
代码:
public class TestMaze {
// 定义一个二维数组做迷宫
private int[][] maze = null;
//表示此迷宫一共有几种走法
private int count = 0;
// 迷宫的开始位置和结束位置的坐标
private static int startI, startJ, endI, endJ;
private void setStart(int startI, int startJ) {
this.startI = startI;
this.startJ = startJ;
}
private void setEnd(int endI, int endJ) {
this.endI = endI;
this.endJ = endJ;
}
/**
* 打印迷宫
*/
private void show() {
System.out.println("第" + (++count) + "种走法");
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
if (maze[i][j] == 0) {// 值为0表示 这条线路不通,打印空格
System.out.print(" ");
} else if (maze[i][j] == 1) {// 值为1 表示,这是通线路 打印*
System.out.print("*");
} else {// 剩下的就是墙壁了 墙壁任然用2表示
System.out.print(maze[i][j]);
}
}
System.out.println();
}
}
/**
* 开始走迷宫
*/
public void play(int x,int y) {
maze[x][y] = 1;
//到达终点
if(x == endI && y == endJ){
show();
}
//否则继续走
//向上走
if(maze[x][y-1] == 0)
play(x,y-1);
//向下走
if(maze[x][y+1] == 0)
play(x,y+1);
//向左走
if(maze[x-1][y] == 0)
play(x-1,y);
//向右走
if(maze[x+1][y] == 0)
play(x+1,y);
//表示当前位置的上下左右都走不通,那么此位置 也不通 重设为0
maze[x][y] = 0;
}
public static void main(String[] args) {
TestMaze myMaze = new TestMaze();
int[][] maze = { { 2, 2, 2, 2, 2, 2, 2, 2 },
{ 2, 0, 0, 0, 0, 2, 2, 2 },
{ 2, 0, 2, 0, 0, 0, 2, 2 },
{ 2, 0, 0, 2, 0, 2, 0, 2 },
{ 2, 0, 0, 2, 0, 2, 2, 0 },
{ 2, 0, 2, 0, 0, 0, 0, 2 },
{ 2, 0, 0, 0, 0, 2, 0, 2 },
{ 2, 2, 2, 2, 2, 2, 2, 2 } };
myMaze.maze = maze;
myMaze.setStart(1, 1);
myMaze.setEnd(6, 6);
myMaze.play(1, 1);
}
}
测试结果: