您的位置:首页 > 其它

bfs 迷宫输出最短路径

2016-05-21 12:10 417 查看
想法:用step[maxn][maxn]数组储存每个位置需要的最小步数

用dir[maxn][maxn]存储上个节点过来的方向,由于是bfs,到这个位置的时候如果步数最小,那么方向一定是唯一的。所以每个位置的dri只会被更新一次

还需要一个visit数组储存是否访问(也可以把map设置成false,因为一个地方被visit以后相当于这里就是墙了)

注意这里涉及到deque的使用,

deque有

push_back

,push_front,

pop_back,

pop_front,

back,

front方法

#include <iostream>
#include <queue>
#include <deque>
using namespace std;
int sx,sy,dx,dy;
const int maxn=10005;
bool visit[maxn][maxn];
int dir[maxn][maxn];
bool map[maxn][maxn];
int step[maxn][maxn];
int M,N;
const int INF=999999;
int tx[]={0,0,-1,1};
int ty[]={-1,1,0,0};
typedef struct{
int x,y;
}Point;
int bfs(int x,int y){
visit[x][y]=true;
queue<Point> Q;
Point cur;
cur.x=x,cur.y=y;
Q.push(cur);
while(!Q.empty()){
cur=Q.front();
Q.pop();
if(cur.x==dx&&cur.y==dy) return step[cur.x][cur.y];
Point next;
for(int i=0;i<4;i++){
next.x=cur.x+tx[i],next.y=cur.y+ty[i];
if(map[next.x][next.y]&&!visit[next.x][next.y]){
Q.push(next);
visit[next.x][next.y]=true;
dir[next.x][next.y]=i+1;
step[next.x][next.y]=step[cur.x][cur.y]+1;
}
}
}
return INF;
}

void print(int x,int y){
deque<Point> path;
Point next;
while(x!=sx||y!=sy){
next.x=x,next.y=y;
path.push_back(next);
if(dir[x][y]==1) y++;
else if(dir[x][y]==2) y--;
else if(dir[x][y]==3) x++;
else if(dir[x][y]==4) x--;
else return ;
}
next.x=sx,next.y=sy;
path.push_back(next);
while(!path.empty()){
next=path.back();
path.pop_back();
printf("(%d,%d)\n",next.x,next.y);
}
}

int main(int argc, char const *argv[])
{
while(cin>>M>>N){
memset(map,false,sizeof(map));
memset(dir,0,sizeof(dir));
memset(visit,false,sizeof(visit));
for(int i=1;i<=M;i++){
for(int j=1;j<=N;j++){
cin>>map[i][j];
}
}
cin>>sx>>sy>>dx>>dy;
cout<<bfs(sx,sy)<<endl;;
print(dx,dy);
// for(int i=1;i<=M;i++){
//  for(int j=1;j<=N;j++){
//      cout<<dir[i][j]<<" ";
//  }
//  cout<<endl;
// }
// cout<<endl;
// for(int i=1;i<=M;i++){
//  for(int j=1;j<=N;j++){
//      cout<<map[i][j]<<" ";
//  }
//  cout<<endl;
// }
// cout<<endl;
// for(int i=1;i<=M;i++){
//  for(int j=1;j<=N;j++){
//      cout<<step[i][j]<<" ";
//  }
//  cout<<endl;
// }
// cout<<endl;
}
/* code */
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: