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)
代码
法一:STL队列
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 6;
const int dx[] = {-1, 0, 1, 0},
dy[] = { 0, 1, 0,-1};
bool g[N][N];
struct node{
int x,y,s,r[30][2]; //r存储路径
};
queue<node> q;
void print(node cur){
for (int i=0; i<=cur.s; i++)
cout<<"("<<cur.r[i][0]<<", "<<cur.r[i][1]<<")\n";
}
void bfs(){
node cur,next;
cur.x=0; cur.y=0; cur.s=0; memset(cur.r,0,sizeof(cur.r));
q.push(cur); g[0][0]=true; //入队 置标记
while (!q.empty()){
cur=q.front(); q.pop();
for (int i=0; i<4; i++){
int x=cur.x+dx[i],y=cur.y+dy[i];
if (x>=0 && x<5 && y>=0 && y<5 && !g[x][y]){
next=cur; next.s=cur.s+1;
next.x=next.r[next.s][0]=x; next.y=next.r[next.s][1]=y;
q.push(next); g[x][y]=true;
if (x==4 && y==4) { print(q.back()); return; } //找到出口
}
}
}
}
int main(){
for (int i=0; i<=4; i++)
for (int j=0; j<=4; j++) cin>>g[i][j];
bfs();
return 0;
}
法二:手动队列
#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][2],head,tail,pre[N*N];
void print(int i){ //递归输出路径
if (pre[i]) print(pre[i]);
cout<<"("<<que[i][0]<<", "<<que[i][1]<<")"<<endl;
}
void bfs(){
que[++tail][0]=0; que[tail][1]=0; //入队
g[0][0] = true;
pre[tail] = head; //记录前驱
while (head<tail){
head++;
for (int i=0; i<4; i++){
int x=que[head][0]+dx[i],y=que[head][1]+dy[i];
if (x>=0 && x<=4 && y>=0 && y<=4 && !g[x][y]){
que[++tail][0]=x; que[tail][1]=y; //入队
g[x][y] = true;
pre[tail] = head; //记录前驱
if (x==4 && y==4){ print(tail); return; } //找到出口
}
}
}
}
int main(){
for (int i=0; i<=4; i++)
for (int j=0; j<=4; j++) cin>>g[i][j];
bfs();
return 0;
}