CH2907 乳草的入侵 BFS

烈酒焚心 提交于 2019-11-29 09:49:58

题目链接

http://noi-test.zzstep.com/contest/0x29%E3%80%8C%E6%90%9C%E7%B4%A2%E3%80%8D%E7%BB%83%E4%B9%A0/2907%20%E4%B9%B3%E8%8D%89%E7%9A%84%E5%85%A5%E4%BE%B5

分析

BFS裸题,每次向周边八个位置扩展即可。

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 105;
const int nxt[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1},
					   {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};

struct Node {
	int x, y;
} st;

int n, m, d[maxn][maxn], ans;
char map[maxn][maxn];
queue<Node> q;

inline int judge(int x, int y) {
	return x > 0 && x <= n && y > 0 && y <= m && map[x][y] != '*';
}

inline void bfs() {
	memset(d, -1, sizeof(d));
	d[st.x][st.y] = 0;
	q.push(st);
	while (!q.empty()) {
		Node u = q.front(), v;
		q.pop();
		ans = max(ans, d[u.x][u.y]);
		for (int i = 0; i < 8; ++i) {
			v.x = u.x + nxt[i][0], v.y = u.y + nxt[i][1];
			if (!judge(v.x, v.y)) continue;
			if (d[v.x][v.y] == -1) {
				d[v.x][v.y] = d[u.x][u.y] + 1;
				q.push(v);
			}
		}
	}
}

int main() {
	m = read(), n = read();
	st.y = read(), st.x = read();
	for (int i = 1; i <= n; ++i) scanf("%s", map[i] + 1);
	bfs();
	printf("%d", ans);
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!