5 5 **..T **.*. ..|.. .*.*. S....
#include<cstdio> #include<queue> using namespace std; int n,m,map[25][25],k,sa,sb; int d[4][2]={-1,0,1,0,0,-1,0,1}; char str[25][25]; typedef struct Lnode{ int x,y,step; friend operator<(Lnode a,Lnode b) { return a.step>b.step; } }node; int bfs(node start) { priority_queue<node> Q; node now,next; now=start; Q.push(now); char c; int i,time=0; while(!Q.empty()) { now=Q.top(); Q.pop(); for(i=0;i<=4;i++) { next.x=now.x+d[i][0]; next.y=now.y+d[i][1]; next.step=now.step+1; if(next.x>=0&&next.y>=0&&next.x<n&&next.y<m&&(str[next.x][next.y]=='-'||str[next.x][next.y]=='|')) { if(!(now.step%2)) c=str[next.x][next.y]; else if(now.step%2) { if(str[next.x][next.y]=='|') c='-'; else c='|'; } if(((d[i][0]==-1&&d[i][1]==0)||(d[i][0]==1&&d[i][1]==0))&&c=='|') { next.x+=d[i][0]; next.y+=d[i][1]; } else if(((d[i][0]==0&&d[i][1]==-1)||(d[i][0]==0&&d[i][1]==1))&&c=='-') { next.x+=d[i][0]; next.y+=d[i][1]; } else if(((d[i][0]==-1&&d[i][1]==0)||(d[i][0]==1&&d[i][1]==0))&&c=='-') { next.x+=d[i][0]; next.y+=d[i][1]; next.step++; } else if(((d[i][0]==0&&d[i][1]==-1)||(d[i][0]==0&&d[i][1]==1))&&c=='|') { next.x+=d[i][0]; next.y+=d[i][1]; next.step++; } } if(next.x>=0&&next.y>=0&&next.x<n&&next.y<m&&map[next.x][next.y]==0) { if(str[next.x][next.y]=='T') return next.step; else if(str[next.x][next.y]=='.') { map[next.x][next.y]=1; Q.push(next); } } } } return -1; } int main() { int i,j,time; while(scanf("%d%d",&n,&m)!=-1) { k=0; for(i=0;i<n;i++) { scanf("%s",str[i]); for(j=0;j<m;j++) { if(str[i][j]=='S') { sa=i;sb=j; } } } memset(map,0,sizeof(map)); node start; start.step=0; start.x=sa; start.y=sb; map[sa][sb]=1; time=bfs(start); printf("%d\n",time); } return 0; }
原文地址:http://blog.csdn.net/jiangx1994/article/details/38225697