题意:给定一个5*5的迷宫,求从左上角到右下角的最短路径。
分析:BFS跑一下最短路,这里学习一下保存输出最短路径的方法。
代码:
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<vector>
#include<set>
#include<string>
#include<sstream>
#include<map>
#include<list>
#include<queue>
using namespace std;
const int MAX_N = 10 ;
int Map[MAX_N][MAX_N] ;
struct node{
int x , y ,s ;
node(int x= 0 , int y=0 ,int s=0):x(x),y(y),s(s){}
};
int book[MAX_N][MAX_N];
node p[MAX_N][MAX_N] ;
int Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
void print_ans(node u){
vector<node> nodes ;
for(;;){
nodes.push_back(u);
if(u.x==0&&u.y==0) break;
u = p[u.x][u.y];
}
//nodes.push_back(node(0,0,0));
for(int i = nodes.size()-1;i>=0;i--){
printf("(%d, %d)\n",nodes[i].x,nodes[i].y);
}
}
void bfs(){
queue<node> q ;
book[0][0] = 1 ;
node s(0,0,0);
q.push(s);
while(!q.empty()){
node n = q.front();
q.pop();
if(n.x==4&&n.y==4){
print_ans(n);
//cout<<n.s<<endl;
break;
}
for(int i = 0 ; i < 4 ; i ++){
int tx = n.x + Next[i][0];
int ty = n.y + Next[i][1];
int ts = n.s + 1 ;
if(tx<0||tx>4||ty<0||ty>4) continue ;
if(book[tx][ty]==0&&Map[tx][ty]==0){
book[tx][ty]= 1 ;
node New(tx,ty,ts);
p[tx][ty] = n;
q.push(New);
}
}
}
return ;
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//ios::sync_with_stdio(false);
memset(book,0,sizeof(book));
for(int i = 0 ; i < 5 ; i++ ){
for(int j = 0 ; j < 5 ; j ++)scanf("%d",&Map[i][j]);
}
bfs();
return 0 ;
}