问题链接:Problem H
问题简述:
给出一幅5*5的地图,1表示墙壁,0表示道路,输出由坐上角到右下角的最短路径。
问题分析:
最短路径问题,可用BFS解决。难点在于如何输出路径。
程序说明:
在结构中定义了一个二维数组,用于存储每一步行走的坐标,用于结果输出路径。坑点在于格式问题“,”后有一个空格。
AC通过的C语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
int map[6][6];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool vis[6][6];
struct node{
int x;
int y;
int route[50][2];
int step;
};
void init(){
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
}
bool edge(int x,int y){
if(x>=0&&y>=0&&x<5&&y<5&&map[x][y]==0&&vis[x][y]==0){
return 1;
}
else
return 0;
}
node BFS(){
queue<node>q;
node p1;
p1.x=0;
p1.y=0;
p1.step=0;
p1.route[0][0]=0;
p1.route[0][1]=0;
vis[0][0]=1;
q.push(p1);
while(!q.empty()){
node p2=q.front();
q.pop();
if(p2.x==4&&p2.y==4){
return p2;
}
for(int i=0;i<4;i++){
int next_x=p2.x+dir[i][0];
int next_y=p2.y+dir[i][1];
if(edge(next_x,next_y)){
p1=p2;
p1.x=next_x;
p1.y=next_y;
p1.step=p2.step+1;
p1.route[p1.step][0]=next_x;
p1.route[p1.step][1]=next_y;
vis[next_x][next_y]=1;
q.push(p1);
}
}
}
}
int main(){
std::ios::sync_with_stdio(false);
init();
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>map[i][j];
}
}
node ans=BFS();
for(int i=0;i<=ans.step;i++){
cout<<"("<<ans.route[i][0]<<", "<<ans.route[i][1]<<")"<<endl;
}
}