Total Submission(s): 15639 Accepted Submission(s): 5673
题意:给出起点和终点走迷宫求最短路(注意起点有多个)
简单bfs(由于有多个起点所以上做下处理 从终点起去搜起点)+优先队列求出最优解
#include<iostream> #include<cstdio> #include<cstring> #include<stack> #include<queue> using namespace std; int n,m,ans,sx,sy; char map[205][205]; int vis[205][205]; int dx[4]={-1,0,1,0}; int dy[4]={0,1,0,-1}; struct node{ friend bool operator<(const node a,const node b) { return a.depth>b.depth;//大的数优先级低 } int x,y,depth; }; int bfs(int x,int y) { int i; node a,t,p; priority_queue<node> q; a.x=x; a.y=y; a.depth=0; q.push(a); while(!q.empty()) { t=q.top(); q.pop(); for(i=0;i<4;i++) { int xx,yy; p.x=t.x+dx[i]; p.y=t.y+dy[i]; if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&!vis[p.x][p.y]) { vis[p.x][p.y]=1; p.depth=t.depth+1; if(map[p.x][p.y]=='x') p.depth++; if(map[p.x][p.y]=='r') return p.depth; q.push(p); } } } return 0; } int main() { char a; int i,j; while(cin>>n>>m) { memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) scanf("%s",&map[i]); for(i=0;i<n;i++) for(j=0;j<m;j++) { if(map[i][j]=='a') { sx=i; sy=j; vis[i][j]=1; } if(map[i][j]=='#') vis[i][j]=1; } ans=bfs(sx,sy); if(ans!=0) printf("%d\n",ans); else cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; } return 0; }
原文地址:http://blog.csdn.net/fanerxiaoqinnian/article/details/38149599