1 条题解
-
0
C++ :
#include<iostream> #include<string.h> #include<stdio.h> #include<ctype.h> #include<algorithm> #include<stack> #include<queue> #include<set> #include<math.h> #include<vector> #include<deque> #include<fstream> #include<list> #define maxn 210 using namespace std; struct N { int x; int y; int step; bool operator<(const N &a)const//两个const不可少 { return a.step<step; } } p; int dis[4][2]= {0,1,0,-1,1,0,-1,0}; int m,n; int ans; char map[maxn][maxn]; bool vis[maxn][maxn]; int sx,sy,ex,ey; bool check(int x,int y) { if(x>=0&&y>=0&&x<m&&y<n&&vis[x][y]==0&&map[x][y]!='#') return true; else return false; } void bfs() { priority_queue<N> pq;//若优先队列是全局变量、则每次都要清空队列 N now,next; now.x=sx; now.y=sy; now.step=0; vis[now.x][now.y]=1; pq.push(now); while(!pq.empty()) { now=pq.top(); pq.pop(); if(now.x==ex&&now.y==ey) { ans=now.step; return ; } for(int i=0; i<4; i++) { next=now; next.x+=dis[i][0]; next.y+=dis[i][1]; if(check(next.x,next.y)) { next.step=now.step+1; vis[next.x][next.y]=1; if(map[next.x][next.y]=='x') next.step+=1; pq.push(next); } } } ans=-1; return ; } int main() { //ofstream cout; //ifstream cin; //cin.open("e.in"); //cout.open("e.out"); int testcase; cin>>testcase; while(testcase--) { cin>>m>>n; ans=0; memset(vis,0,sizeof(vis)); memset(map,0,sizeof(map)); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cin>>map[i][j]; if(map[i][j]=='a') { sx=i; sy=j; } if(map[i][j]=='r') { ex=i; ey=j; } } } bfs(); if(ans!=-1) cout<<ans<<endl; else cout<<"Poor XIAOMING has to stay in the prison all his life."<<endl; } return 0; }
- 1
信息
- ID
- 1338
- 时间
- 5000ms
- 内存
- 128MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者