5.14每日鮮例題(一)UVA 11624 BFS

一個稍微複雜一點的搜索

首先預處理每個格子起火的時間,J進行轉移的時候加上下一個格子在下一時刻是否會着火或是否已經着火的判斷即可

#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
char e[maxn][maxn];
int t[maxn][maxn];
bool book[maxn][maxn];
struct node{
	int x,y,t;
	node(int x_,int y_,int t_){
		x=x_;y=y_;t=t_;
	}
};
int r,c;
int mo[4][2]={0,1,1,0,-1,0,0,-1};
queue<node>q1;
queue<node>q2;
void init(){
	cin>>r>>c;
	while(!q1.empty()) q1.pop();
	while(!q2.empty()) q2.pop();
	memset(t,-1,sizeof(t));
	memset(book,0,sizeof(book));
	for(int i=0;i<r;i++){
		char s[maxn];
		scanf("%s",s);
		for(int j=0;j<c;j++){
			e[i][j]=s[j];
			if(e[i][j]=='F'){
				q1.push(node(i,j,0)); 
				t[i][j]=0;
			} 
			else if(e[i][j]=='J') q2.push(node(i,j,0));
		}
	}
}
void bfs1(){//預處理每個格子起火事件
	 while(!q1.empty()){
	 	node temp=q1.front();q1.pop();
	 	int x=temp.x,y=temp.y;
	 	for(int i=0;i<4;i++){
	 		int nx=x+mo[i][0];
	 		int ny=y+mo[i][1];
	 		
	 		if(nx<0||ny<0||nx>=r||ny>=c) continue;
	 		if(e[nx][ny]=='#') continue;
	 		if(t[nx][ny]>=0) continue;
	 		
	 		t[nx][ny]=temp.t+1;
	 		q1.push(node(nx,ny,t[nx][ny]));
		 }
	 }
}
int ans;
void bfs2(){
	book[q2.front().x][q2.front().y]=1;
	while(!q2.empty()){
		node temp=q2.front();q2.pop();
		int x=temp.x,y=temp.y;
		if(x==0||y==0||x==r-1||y==c-1) {
			ans=temp.t+1;
			break;
		}
		for(int i=0;i<4;i++){
			int nx=x+mo[i][0];
			int ny=y+mo[i][1];
			if(book[nx][ny]) continue;
			if(nx<0||ny<0||nx>=r||ny>=c) continue;
	 		if(e[nx][ny]=='#') continue;
	 		if(t[nx][ny]<=temp.t+1&&t[nx][ny]!=-1) continue;
	 		
	 		book[nx][ny]=1;
	 		q2.push(node(nx,ny,temp.t+1));
		}
	}
}
int main()
{
	int T;
	cin>>T;
	while(T--){
		ans=0;
		init();
		bfs1();
		bfs2();
		if(ans) cout<<ans<<endl;
		else cout<<"IMPOSSIBLE"<<endl;
	}
	return 0;
 } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章