1. 程式人生 > 其它 >218. 天際線問題

218. 天際線問題

題目編號:UVA - 11624

https://vjudge.net/problem/UVA-11624#author=zmyhh

此題需要注意,不能無腦使用while(!r.empty()),只能讓兩個一步一步走。

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<queue>
 7 using namespace std;
 8 #define
ll long long 9 struct poi 10 { 11 int x,y,step; 12 }; 13 int t,n,m; 14 char s[1007][1007]; 15 int dx[4]={0,0,-1,1}; 16 int dy[4]={1,-1,0,0}; 17 int main() 18 { 19 cin>>t; 20 while(t--){ 21 cin>>n>>m; 22 int px,py,fx,fy; 23 poi a; 24 queue<poi>rf,rp;
25 for(int i=1;i<=n;i++){ 26 getchar(); 27 for(int j=1;j<=m;j++){ 28 s[i][j]=getchar(); 29 if(s[i][j]=='F'){ 30 rf.push({i,j,0}); 31 } 32 if(s[i][j]=='J'){ 33 rp.push({i,j,0
}); 34 } 35 } 36 } 37 int f,p; 38 int xx,yy,flag=1; 39 while(!rp.empty()){//若人走完所有可能性,無答案輸出,輸出不可能 40 f=rf.front().step;//只走當前步數,下一步不走 41 while(!rf.empty()){//F 42 a=rf.front(); 43 if(a.step!=f){//到了下一步,跳出,開始走人 44 break; 45 } 46 rf.pop(); 47 for(int i=0;i<4;i++){ 48 xx=dx[i]+a.x; 49 yy=dy[i]+a.y; 50 if(s[xx][yy]!='F'&&s[xx][yy]!='#'&&xx>=1&&yy>=1&&xx<=n&&yy<=m){//遇到牆和火不走 51 rf.push({xx,yy,a.step+1}); 52 s[xx][yy]='F';//標記 53 } 54 } 55 } 56 p=rp.front().step;//同上 57 while(!rp.empty()){ 58 a=rp.front(); 59 if(p!=rp.front().step){ 60 break; 61 } 62 rp.pop(); 63 for(int i=0;i<4;i++){ 64 xx=dx[i]+a.x; 65 yy=dy[i]+a.y; 66 if(flag&&(xx<1||yy<1||xx>n||yy>m)){ 67 cout<<a.step+1<<endl; 68 flag=0;//找到答案,跳出 69 } 70 if(s[xx][yy]!='#'&&s[xx][yy]!='F'&&s[xx][yy]!='J'){//遇到牆,火,人不走 71 rp.push({xx,yy,a.step+1}); 72 s[xx][yy]='J'; 73 } 74 } 75 if(flag==0){ 76 break; 77 } 78 } 79 if(flag==0){ 80 break; 81 } 82 } 83 if(flag){ 84 cout<<"IMPOSSIBLE"<<endl; 85 } 86 } 87 return 0; 88 }