ybt1255_迷宫问题
时空限制 1000ms/64MB
【题目描述】
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
【输入】
一个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
【输出样例】
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
代码
#include<iostream>
using namespace std;
const int N = 6;
const int dx[] = {-1, 0, 1, 0},
dy[] = { 0, 1, 0,-1};
bool g[N][N];
int que[N*N][3],pre[N*N];
void print(int i){
if (pre[i]!=0) print(pre[i]);
cout<<"("<<que[i][1]<<", "<<que[i][2]<<")"<<endl;
}
int main(){
for (int i=0; i<5; i++)
for (int j=0; j<5; j++) cin>>g[i][j];
int head=0,tail=1;
que[1][1]=0; que[1][2]=0; pre[1]=0;
g[0][0] = true;
while (head<tail){
head++;
for (int i=0; i<4; i++){
int x=que[head][1]+dx[i],y=que[head][2]+dy[i];
if (x>=0 && x<5 && y>=0 && y<5 && !g[x][y]){
tail++;
que[tail][1]=x;
que[tail][2]=y;
pre[tail]=head;
g[x][y] = true;
if (x==4 && y==4){
print(tail);
return 0;
}
}
}
}
}