HDU 2102 A计划 BFS
#include<iostream> #include<string> #include<string.h> #include<stdio.h> #include<math.h> #include<queue> #include<algorithm> using namespace std; int n,m,T,di,dj,ok,f; char mapp[2][15][15]; int vis[2][15][15]; struct node{ int x,y; int step; int floor; //在第几层 friend bool operator < (node a,node b){ return a.step > b.step; //升序 } }; int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; priority_queue<node> pq; void bfs(){ node temp,next; int s,d; while(!pq.empty()){ temp=pq.top(); // cout<<temp.floor<<" "<<temp.x<<" "<<temp.y<<" "<<temp.step<<endl; pq.pop(); if(temp.step>T) {break;} if(temp.x==di&&temp.y==dj&&temp.step<=T&&temp.floor==f) { ok=1; break; } if(mapp[temp.floor][temp.x][temp.y]=='.'){ for(int i=0;i<4;i++){ s=temp.x+dir[i][0]; d=temp.y+dir[i][1]; if(s>=0&&s<n&&d>=0&&d<m&&vis[temp.floor][s][d]==0&&mapp[temp.floor][s][d]!='*'){ vis[temp.floor][s][d]=1; next.floor=temp.floor; next.x=s; next.y=d; next.step=temp.step+1; // cout<<temp.floor<<" "<<s<<" "<<d<<" "<<next.step<<" 是. "<<endl; pq.push(next); } } }if(mapp[temp.floor][temp.x][temp.y]=='#'){ int ff=(temp.floor+1)%2; if(mapp[ff][temp.x][temp.y]!='*'&&vis[ff][temp.x][temp.y]==0){ vis[ff][temp.x][temp.y]=1; next.floor=ff; next.x=temp.x; next.y=temp.y; next.step=temp.step; // cout<<ff<<" "<<temp.x<<" "<<temp.y<<" "<<temp.step<<" 是 # "<<endl; pq.push(next); } } } } int main(){ int t; cin>>t; while(t--){ cin>>n>>m>>T; memset(vis,0,sizeof(vis)); while(!pq.empty()) pq.pop(); ok=0; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ cin>>mapp[0][i][j]; if(mapp[0][i][j]=='P'){di=i;dj=j;f=0;} } for(int i=0;i<n;i++) for(int j=0;j<m;j++){ cin>>mapp[1][i][j]; if(mapp[1][i][j]=='P'){di=i;dj=j;f=1;} } node tt; tt.x=0;tt.y=0;tt.step=0;tt.floor=0; mapp[0][0][0]='.'; vis[0][0][0]=1; pq.push(tt); bfs(); if(ok) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }