Fire!

可以标记下每个点被燃烧的时间点,这样只要在这个时间点前到达的话,就可以走到这个点。两次BFS(),感觉真是太奇妙了。还有坑点,就是这地方有草,但Sample Input
2
4 4
####
#JF#
#..#
#..#
3 3
###
#J.

#.F

Sample Output
3
IMPOSSIBLE

是可能烧不到,一定要注意这种情况,就是标记能不能烧到

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
char map[1005][1005];
int vis[1005][1005];
int time1[1005][1005];//火到达这点的时间;
int n, m;
int a, b;
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,-1,1 };
struct node {
	int x, y;
	int time;
};
int  bfs() {
	node now, next;
	queue<node>q;
	memset(vis, 0, sizeof(vis));
	now.x = a, now.y = b, now.time = 0;
	vis[a][b] = 1;
	q.push(now);
	while (!q.empty()) {
		now = q.front();
		q.pop();
		if (now.x == 0 || now.x == n-1 || now.y == 0 || now.y == m-1) {
			return now.time+1;
		}
		next.time = now.time + 1;
		for (int i = 0; i < 4; i++) {
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if (next.x >= 0 && next.x < n&&next.y >= 0 && next.y<m&&map[next.x][next.y] == '.' && !vis[next.x][next.y] && next.time<time1[next.x][next.y])
			{
				vis[next.x][next.y] = 1;
				
				q.push(next);
			}

		}
	}
	return -1;

}
int main() {
	int t;
	cin >> t;
	
	memset(vis, 0, sizeof(vis));
	while (t--) {
		memset(time1, -1, sizeof(time1));
		cin >> n >> m;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cin >> map[i][j];
			}
		}
		queue<node>q;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (map[i][j] == 'J') {
					a = i;
					b = j;
				}
				else if (map[i][j] == 'F') {
					node now;
					now.x = i, now.y = j;
					time1[i][j] = 0;
					q.push(now);
					vis[now.x][now.y] = 1;
				}
			}
		}
		node aa, next;
		while (!q.empty()) {
			aa = q.front();
			q.pop();
			for (int i = 0; i < 4; i++) {
				next.x = aa.x + dx[i];
				next.y = aa.y + dy[i];
				if (vis[next.x][next.y]||next.x < 0 || next.x >= n || next.y<0 && next.y>=m || map[next.x][next.y] == '#') {
					continue;
				}
				vis[next.x][next.y] = 1;
				time1[next.x][next.y] = time1[aa.x][aa.y] + 1;
				q.push(next);
			}
		}
		int ans = bfs();
		if (ans == -1)
			printf("IMPOSSIBLE\n");
		else
			printf("%d\n", ans);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值