标签:
Input
Output
Sample Input
3 4 YBEB EERE SSTE 0 0
Sample Output
8
1 /*由于碰到brick walls步数会增2,所以要用优先队列,优先选取步数最小的进行扩展*/ 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 using namespace std; 6 7 char map[305][305]; 8 bool visit[305][305]; 9 int sx,sy,ex,ey,m,n; 10 int d[4][2]={1,0,0,1,-1,0,0,-1}; 11 12 struct point 13 { 14 int x; 15 int y; 16 int step; 17 bool operator <(const point &temp)const 18 { 19 return step>temp.step; 20 } 21 }; 22 23 int BFS() 24 { 25 point init; 26 init.x=sx; 27 init.y=sy; 28 init.step=0; 29 priority_queue<point>q; 30 q.push(init); 31 visit[init.x][init.y]=true; 32 point node,newnode; 33 while(!q.empty()) 34 { 35 node=q.top(); 36 q.pop(); 37 if(node.x==ex&&node.y==ey) 38 return node.step; 39 for(int i=0;i<4;i++) 40 { 41 newnode.x=node.x+d[i][0]; 42 newnode.y=node.y+d[i][1]; 43 if(newnode.x>=0&&newnode.x<m&&newnode.y>=0&&newnode.y<n&&!visit[newnode.x][newnode.y]) 44 if(map[newnode.x][newnode.y]!=‘S‘&&map[newnode.x][newnode.y]!=‘R‘) 45 { 46 if(map[newnode.x][newnode.y]==‘B‘) 47 newnode.step=node.step+2; 48 else 49 newnode.step=node.step+1; 50 q.push(newnode); 51 visit[newnode.x][newnode.y]=true;//这个一开始写外面了一直TLE 52 } 53 } 54 } 55 return -1; 56 } 57 58 int main() 59 { 60 //freopen("in.txt","r",stdin); 61 int i,j; 62 while(scanf("%d%d",&m,&n),m||n) 63 { 64 memset(visit,false,sizeof(visit)); 65 getchar(); 66 for(i=0;i<m;i++) 67 { 68 for(j=0;j<n;j++) 69 { 70 scanf("%c",&map[i][j]); 71 if(map[i][j]==‘Y‘) 72 sx=i,sy=j; 73 else if(map[i][j]==‘T‘) 74 ex=i,ey=j; 75 else; 76 } 77 getchar(); 78 } 79 int ans=BFS(); 80 printf("%d\n",ans); 81 } 82 return 0; 83 }
标签:
原文地址:http://www.cnblogs.com/homura/p/4691655.html