标签:c++
5 5 **..T **.*. ..|.. .*.*. S....
7地图如下:HintHint#include<iostream> #include<cstdio> #include<cstring> #include<queue> #define qq 22 using namespace std; char map[qq][qq]; int vis[qq][qq]; struct node { int x,y,step; bool operator <(const node & t) const { return step>t.step; //模板 小的先出队列 } }; int fx1[5]= {0,0,1,-1}; int fx2[5]= {1,-1,0,0}; int m,n; int sx,sy,ex,ey; void bfs() { priority_queue<node>q; node now,next; now.x=sx; now.y=sy; now.step=0; q.push(now); vis[sx][sy]=1; while(!q.empty()) { now=q.top(); q.pop(); if(map[now.x][now.y]=='T') { cout<<now.step<<endl; return; } for(int i=0; i<4; i++) { next.x=now.x+fx1[i]; next.y=now.y+fx2[i]; if(next.x<1||next.y<1||next.x>m||next.y>n||vis[next.x][next.y]==1) continue; if(map[next.x][next.y]=='|') //遇到楼梯 { if(now.step%2==0&&(i==3||i==2)) { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; } else if(now.step%2==1&&(i==0||i==1)) { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; } else //不能经过楼梯时 { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; vis[next.x][next.y]=1; next.step=now.step+2; //step+2 这也就是用优先队列的原因 q.push(next); continue; //不能和下面重复 一定要加 } } if(map[next.x][next.y]=='-') { if(now.step%2==0&&(i==0||i==1)) { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; } else if(now.step%2==1&&(i==3||i==2)) { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; } else { next.x=next.x+fx1[i]; next.y=next.y+fx2[i]; vis[next.x][next.y]=1; next.step=now.step+2; q.push(next); continue; } } vis[next.x][next.y]=1; next.step=now.step+1; q.push(next); } } return; } int main() { int i,j; while(~scanf("%d%d",&m,&n)) { memset(vis,0,sizeof(vis)); for(i=1; i<=m; i++) for(j=1; j<=n; j++) { cin>>map[i][j]; if(map[i][j]=='*') //标记墙壁 vis[i][j]=1; if(map[i][j]=='S') //记录起点 { sx=i; sy=j; } } bfs(); } return 0; }
标签:c++
原文地址:http://blog.csdn.net/axuan_k/article/details/38149407