标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25081 Accepted Submission(s): 8887
走卫兵守护的路花费的时间多1,考虑优先队列
#include<cstdio> #include<cstring> #include<algorithm> #include<math.h> #include<queue> #include<iostream> using namespace std; typedef long long LL; char graph[205][205]; bool vis[205][205]; struct Node { int x,y; int step; }; Node s,t; bool operator < (Node a,Node b) { return a.step>b.step; } int n,m; int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}}; bool check(int x,int y) { if(x<0||x>=n||y<0||y>=m||graph[x][y]==‘#‘||vis[x][y]==true) return false; return true; } int bfs() { memset(vis,false,sizeof(vis)); priority_queue<Node> q; q.push(s); vis[s.x][s.y]=true; s.step = 0; while(!q.empty()) { Node now = q.top(); q.pop(); if(now.x==t.x&&now.y==t.y) { return now.step; } Node next; for(int i=0; i<4; i++) { next.x = now.x+dir[i][0]; next.y = now.y+dir[i][1]; if(!check(next.x,next.y)) continue; if(graph[next.x][next.y]==‘x‘) { next.step=now.step+2; q.push(next); vis[next.x][next.y]=1; } else if(graph[next.x][next.y]==‘.‘) { next.step=now.step+1; q.push(next); vis[next.x][next.y]=1; } } } return -1; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { for(int i=0; i<n; i++) { scanf("%s",graph[i]); for(int j=0; j<m; j++) { if(graph[i][j]==‘r‘) { s.x=i,s.y=j; graph[i][j]=‘.‘; } if(graph[i][j]==‘a‘) { t.x=i,t.y=j; graph[i][j]=‘.‘; } } } int res = bfs(); if(res==-1) { printf("Poor ANGEL has to stay in the prison all his life.\n"); } else printf("%d\n",res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5573719.html