定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
import java.util.*;
public class Main{
static ArrayList<A> A;
static int x[][],y[][],num;
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
x=new int[5][5];
y=new int[5][5];
A=new ArrayList<A>();
for(int n=0;n<5;n++){
for(int m=0;m<5;m++){
x[n][m]=reader.nextInt();
}
}
A xx=new A();
xx.x=0;
xx.y=0;
xx.step=0;
A.add(xx);
f();
A.clear();
num=y[4][4];
//System.out.println(num);
ff(4,4);
for(int n=A.size()-1;n>=0;n--){
System.out.println("("+A.get(n).x+", "+A.get(n).y+")");
}
//System.out.println(num);
}
public static void f(){
for(;;){
A xx=A.get(0);
A.remove(0);
if(xx.x==4&&xx.y==4)break;
if(xx.x+1<5&&x[xx.x+1][xx.y]==0&&y[xx.x+1][xx.y]==0){
y[xx.x+1][xx.y]=xx.step+1;
A yy=new A();
yy.x=xx.x+1;
yy.y=xx.y;
yy.step=xx.step+1;
A.add(yy);
}
if(xx.y+1<5&&x[xx.x][xx.y+1]==0&&y[xx.x][xx.y+1]==0){
y[xx.x][xx.y+1]=xx.step+1;
A yy=new A();
yy.x=xx.x;
yy.y=xx.y+1;
yy.step=xx.step+1;
A.add(yy);
}
if(xx.x-1>=0&&x[xx.x-1][xx.y]==0&&y[xx.x-1][xx.y]==0){
y[xx.x-1][xx.y]=xx.step+1;
A yy=new A();
yy.x=xx.x-1;
yy.y=xx.y;
yy.step=xx.step+1;
A.add(yy);
}
if(xx.y-1>=0&&x[xx.x][xx.y-1]==0&&y[xx.x][xx.y-1]==0){
y[xx.x][xx.y-1]=xx.step+1;
A yy=new A();
yy.x=xx.x;
yy.y=xx.y-1;
yy.step=xx.step+1;
A.add(yy);
}
}
}
public static void ff(int a,int b){
A xx=new A();
//System.out.println(a+" "+b+" "+y[a][b]+" "+num);
if((a==1&&b==0)||(a==0&&b==1)){
A xxx=new A();
xxx.x=a;
xxx.y=b;
A.add(xxx);
xx.x=0;
xx.y=0;
A.add(xx);
return;
}
if(a+1<5&&y[a+1][b]==y[a][b]-1){
num--;
xx.x=a;
xx.y=b;
A.add(xx);
ff(a+1,b);
}
if(b+1<5&&y[a][b+1]==y[a][b]-1){
num--;
xx.x=a;
xx.y=b;
A.add(xx);
ff(a,b+1);
}
if(a-1>=0&&y[a-1][b]==y[a][b]-1){
num--;
xx.x=a;
xx.y=b;
A.add(xx);
ff(a-1,b);
}
if(b-1>=0&&y[a][b-1]==y[a][b]-1){
num--;
xx.x=a;
xx.y=b;
A.add(xx);
ff(a,b-1);
}
return;
}
}
class A{
int x;
int y;
int step;
}