Description
定义一个二维数组:
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) (4, 4)
Source
import java.util.Arrays;
import java.util.Scanner;
class POJ3984{
int x;
int y;
int index;
}//index是存放其父亲的下标,以便输出路径
public class Main{
static int dis[][]={{0,1},{0,-1},{1,0},{-1,0}};//广搜的四个方向
static int e[][]=new int[5][5];//存放迷宫
static boolean book[][]=new boolean[5][5];//标记数组,标记
static POJ3984 p[]=new POJ3984[50];//模拟队列
static int front=0,tail=1;//队列的首尾
static void print(int k){//递归输出路径,先找到祖宗从上往下输出 祖宗的父亲为-1
if(p[k].index!=-1){
print(p[k].index);
System.out.println("("+p[k].x+", "+p[k].y+")");
}
}
static void bfs(){
p[0]=new POJ3984();
p[0].x=0;
p[0].y=0;
p[0].index=-1;//祖宗的父亲为-1
while(front<tail){//判断模拟队列是否为空
for(int i=0;i<4;i++){
int tx=p[front].x+dis[i][0];
int ty=p[front].y+dis[i][1];//向下一层广搜
if(tx<0||tx>=5||ty<0||ty>=5||book[tx][ty]==true||e[tx][ty]==1) continue;//超界,已被标记,或是墙,跳过
book[tx][ty]=true;
p[tail]=new POJ3984();
p[tail].x=tx;
p[tail].y=ty;
p[tail].index=front;//满足条件,标记后加入队列
tail++;
if(tx==4&&ty==4) print(front);//到达终点
}
front++;//出队
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
for(int i=0;i<5;i++){
Arrays.fill(e[i],0);
Arrays.fill(book[i],false);
}
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
e[i][j]=sc.nextInt();
System.out.println("(0, 0)");
bfs();
System.out.println("(4, 4)");
}
}