标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 9929 Accepted Submission(s): 2465
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<algorithm> #include<cstdlib> #include<queue> #include<vector> #include<stack> using namespace std; int n,m,sx,sy,ex,ey,ans; int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; char s[30][30]; bool vis[30][30]; struct node { int x,y,step; friend bool operator<(node a,node b) { return a.step>b.step; } }; bool check(int x,int y) { if(x<0||y<0||x>=n||y>=m||vis[x][y]||s[x][y]==‘*‘) return false; return true; } void bfs() { priority_queue<node> q; node fr; int nx,ny; memset(vis,0,sizeof(vis)); fr.x=sx,fr.y=sy,fr.step=0; vis[sx][sy]=1; q.push(fr); while(!q.empty()) { fr=q.top(),q.pop(); if(fr.x==ex&&fr.y==ey) { ans=fr.step; break; } for(int i=0;i<4;i++) { nx=fr.x+dx[i],ny=fr.y+dy[i]; if(!check(nx,ny)) continue; if(s[nx][ny]==‘.‘||s[nx][ny]==‘T‘) { node temp; temp.x=nx,temp.y=ny; temp.step=fr.step+1; vis[nx][ny]=1; q.push(temp); } else if(i==0||i==1) { if(s[nx][ny]==‘-‘&&(fr.step%2==0)) { node temp; nx+=dx[i],ny+=dy[i]; if(!check(nx,ny)) continue; vis[nx][ny]=1; temp.x=nx,temp.y=ny; temp.step=fr.step+1; q.push(temp); } else if(s[nx][ny]==‘|‘&&(fr.step%2==1)) { node temp; nx+=dx[i],ny+=dy[i]; if(!check(nx,ny)) continue; vis[nx][ny]=1; temp.x=nx,temp.y=ny; temp.step=fr.step+1; q.push(temp); } else { node temp; temp.x=fr.x,temp.y=fr.y; temp.step=fr.step+1; q.push(temp); } } else if(i==2||i==3) { if(s[nx][ny]==‘|‘&&(fr.step%2==0)) { node temp; nx+=dx[i],ny+=dy[i]; if(!check(nx,ny)) continue; vis[nx][ny]=1; temp.x=nx,temp.y=ny; temp.step=fr.step+1; q.push(temp); } else if(s[nx][ny]==‘-‘&&(fr.step%2==1)) { node temp; nx+=dx[i],ny+=dy[i]; if(!check(nx,ny)) continue; vis[nx][ny]=1; temp.x=nx,temp.y=ny; temp.step=fr.step+1; q.push(temp); } else { node temp; temp.x=fr.x,temp.y=fr.y; temp.step=fr.step+1; q.push(temp); } } } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0;i<n;i++) scanf("%s",s[i]); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(s[i][j]==‘S‘) sx=i,sy=j; else if(s[i][j]==‘T‘) ex=i,ey=j; } } bfs(); printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/a972290869/p/4355191.html