UVA11624 Fire!

知识点:广度优先搜索

难度:5

这个题的总的思路不难,就是预处理的思想,我们先用一个bfs来预处理火到达每个格子的时间,然后我们第二个bfs的时候,如果到达这个格子的时间小于火的时间那么就是可以到达的,但是这个题有几个坑点,那就是火的个数可能不是一个,可能没有,也可能多个,,,这是最坑的,然后就是输出的时候要加一,因为到了地图的边缘还要再走一步才出去,

至于有多个火源,那么一开始入队的时候都入队就行了,不影响后面的广搜的过程

总之这个题看了不到一分钟就想到了两个bfs的做法,但是这个火的个数坑了十几分钟

#include <bits/stdc++.h>

using namespace std;

const int N = 1005;

struct node {
	int x, y;
	node() {}
	node(int a, int b): x(a), y(b) {}
};

int n, m, xs, ys, t1[N][N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
vector<pair<int, int>> v;
string s[N];

void bfs1() {
	queue<node> q;
	fill(t1[0], t1[0] + N * N, 1e9);
	for (int i = 0; i < (int) v.size(); i++) {
		q.push(node(v[i].first, v[i].second));
		t1[v[i].first][v[i].second] = 0;
	}
	while (!q.empty()) {
		node now = q.front(); q.pop();
		for (int i = 0; i < 4; i++) {
			int x1 = now.x + dx[i];
			int y1 = now.y + dy[i];
			if (x1 < 1 || x1 > n || y1 < 1 || y1 > m) continue;
			if (s[x1][y1] == '#' || t1[x1][y1] != 1e9) continue;
			q.push(node(x1, y1));
			t1[x1][y1] = t1[now.x][now.y] + 1;
		}
	}
}

int bfs2() {
	queue<node> q;
	q.push(node(xs, ys));
	int dist[N][N];
	fill(dist[0], dist[0] + N * N, -1);
	dist[xs][ys] = 0;
	while (!q.empty()) {
		node now = q.front(); q.pop();
		if (now.x == 1 || now.x == n || now.y == 1 || now.y == m) {
			return dist[now.x][now.y];
		}
		for (int i = 0; i < 4; i++) {
			int x1 = now.x + dx[i];
			int y1 = now.y + dy[i];
			if (x1 < 1 || x1 > n || y1 < 1 || y1 > m) continue;
			if (dist[x1][y1] != -1 || s[x1][y1] == '#') continue;
			if (t1[x1][y1] <= dist[now.x][now.y] + 1) continue;
			q.push(node(x1, y1));
			dist[x1][y1] = dist[now.x][now.y] + 1;
		}
	}
	return -1;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		v.clear();
		cin >> n >> m;
		for (int i = 1; i <= n; i++) {
			cin >> s[i];
			s[i] = " " + s[i];
			for (int j = 1; j <= m; j++) {
				if (s[i][j] == 'J') { xs = i; ys = j; s[i][j] = '.'; }
				if (s[i][j] == 'F') { v.push_back(make_pair(i, j)); s[i][j] = '.'; }
			}
		}
		bfs1();
		int tmp = bfs2();
		if (tmp == -1) cout << "IMPOSSIBLE\n";
		else cout << tmp + 1 << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值