递归经典应用,回溯算法走迷宫
迷宫是自己生成的,当然也可以用算法生成迷宫
public class Maze {
private int[][] maze;//迷宫二维数组
private int starti;//迷宫起始点i
private int startj;//迷宫起始点j
private int endi;//迷宫终点i
private int endj;//迷宫终点j
Maze(){
//初始化迷宫
maze = new int[][]{
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 0, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 1, 1},
{1, 1, 0, 1, 1, 0, 1, 0, 0, 1},
{1, 0, 0, 1, 0, 0, 1, 1, 0, 1},
{1, 0, 1, 1, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 1, 1, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};//初始化迷宫
starti = 1;
startj = 1;
endi = maze.length-2;
endj = maze[0].length-2;
setway(starti,startj);
print();
}
public boolean setway(int i,int j){//回溯算法寻找终点
if(maze[endi][endj] == 2)
return true;
else
{
if(maze[i][j] == 0)//该点未走过
{
maze[i][j] = 2;
if(setway(i,j+1))//右
return true;
else if(setway(i+1,j))//下
return true;
else if(setway(i-1,j))//上
return true;
else if(setway(i,j-1))//左
return true;
maze[i][j] = 0;//该方向走不通就回溯成1
}
else
return false;
}
return false;
}
public void print(){
for(int[] hang:maze)
{
for (int m:hang)
{
if(m == 2)
System.out.print('*'+" ");
else
System.out.print(m+" ");
}
System.out.println();
}
}
}