问题描述:
无,详见其他人的文章
代码:
package test;
public class Maze {
static int count=0;
public static void main(String[] args) {
int maze[][]={
{1,1,1,1,1,1},
{1,0,0,0,1,1},
{1,0,1,0,0,1},
{1,0,0,0,1,1},
{1,1,0,0,0,1},
{1,1,1,1,1,1}
};
Path path=new Path();
path.length=0;//迷宫长度初始化
backTrackMaze(maze,1,1,path);//从1,1到4,4
}
private static void backTrackMaze(int[][] maze, int xi, int yi, Path path) {
int di=0,i=0,j=0;
if(xi==4&&yi==4){//找到一条路
path.point[path.length].i=xi;
path.point[path.length].j=yi;
path.length++;
displayPath(path);
}
else {
if(maze[xi][yi]==0)
{
while(di<4){//
path.point[path.length].i=xi;
path.point[path.length].j=yi;
path.length++;
switch (di) {//上下左右
case 0:i=xi-1;j=yi;break;
case 1:i=xi;j=yi+1;break;
case 2:i=xi+1;j=yi;break;
case 3:i=xi;j=yi-1;break;
// case 0:xi=xi-1;yi=yi;break;
// case 1:xi=xi;yi=yi+1;break;
// case 2:xi=xi+1;yi=yi;break;
// case 3:xi=xi;yi=yi-1;break;
}
maze[xi][yi]=-1;//避免重复找路径
backTrackMaze(maze,i,j,path);
maze[xi][yi]=0;//恢复可走路径
path.length--;//回退一个方格
di++;
}
}
}
}
private static void displayPath(Path path) {
++count;
System.out.println("第"+count+"条迷宫路径:");
for(int k=0;k<path.length;k++)
{
System.out.print("("+path.point[k].i+","+path.point[k].j+")"+" ");
}
System.out.println();
}
}
class Point{
int i,j;
public Point(){
}
}
class Path{
Point point[];
int length;
public Path(){
point=new Point[20];
for(int i=0;i<20;i++)//对象数组初始化,否则空指针
{
point[i]=new Point();
}
}
}
输出:
第1条迷宫路径:
(1,1) (1,2) (1,3) (2,3) (3,3) (4,3) (4,4)
第2条迷宫路径:
(1,1) (1,2) (1,3) (2,3) (3,3) (3,3) (3,2) (4,2) (4,3) (4,4)
第3条迷宫路径:
(1,1) (1,2) (1,1) (2,1) (3,1) (3,2) (3,3) (4,3) (4,4)
第4条迷宫路径:
(1,1) (1,2) (1,1) (2,1) (3,1) (3,2) (3,2) (4,2) (4,3) (4,4)