http://ybt.ssoier.cn:8088/problem_show.php?pid=1255
【题目描述】
定义一个二维数组:
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)
对于这类最短路径型题目,用宽搜的方式处理会比较方便,由于这道题,需要记录路径,可以用struct node{int x1;int y1} 类型的二维数组fp[][]记录,即fp[i][j]表示(i,j)来自(fp[i][j].x1,fp[i][j].y1),这一步是解决这道题的关键。
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int maze[6][6];
bool flag[6][6];
struct node{
int x1;
int y1;
};
queue<node> qu;
node fp[6][6];//node类型的fp[i][j]用于记录(i,j)点的上一个点
int a[]={1,-1,0,0};
int b[]={0,0,1,-1};
void print(int x,int y){
if(x==0&&y==0) cout<<"("<<x<<", "<<y<<")"<<endl;
else{
print(fp[x][y].x1,fp[x][y].y1);
//这两行是输出的关键,用递归的方式,按照从左上角开始的顺序,输出路径。
cout<<"("<<x<<", "<<y<<")"<<endl;//而且顺序不可以反
}
return ;
}
void bfs(){
node t;
t.x1=0;
t.y1=0;
qu.push(t);
while(!qu.empty()){
node now=qu.front();
qu.pop();
if(now.x1==4&&now.y1==4){//当走到终点时
print(4,4);
break;
}
for(int i=0;i<4;i++){
int xx=now.x1+a[i];
int yy=now.y1+b[i];
if(xx<0||xx>=5||yy<0||yy>=5) continue;
if(flag[xx][yy]){
node temp;
temp.x1=xx;
temp.y1=yy;
qu.push(temp);
fp[xx][yy].x1=now.x1;
fp[xx][yy].y1=now.y1;//这一步不能弄错
flag[xx][yy]=false;
}
}
}
return ;
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>maze[i][j];
if(maze[i][j]==0) flag[i][j]=true;
}
}
bfs();
return 0;
}