版权声明:本文为博主原创作品, 转载请注明出处! https://blog.csdn.net/solider98/article/details/84324940
思路分析:
考虑使用BFS, 扩展队头结点时将队头结点的上, 下, 左, 右, 左上, 左下, 右上, 右下未被访问的草地入队即可, 具体实现如下AC代码所示:
//CH2907_乳草的入侵
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
const int MAX = 105, INF = 0x3f3f3f3f;
const int dx[8] = {0, -1, -1, -1, 0, 1, 1, 1}, dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
char G[MAX][MAX]; int R, C, mx, my;
int d[MAX][MAX];//d[i][j]: 位置i行j列处的草地被占领的星期数
int main(){
int tx, ty; scanf("%d %d %d %d", &C, &R, &tx, &ty), mx = R - ty + 1, my = tx;
for(int i = 1; i <= R; ++i) scanf("%s", G[i] + 1);
memset(d, 0x3f, sizeof(d)), d[mx][my] = 0; queue<pii> qu; qu.push(mp(mx, my));
while(!qu.empty()){
int x = qu.front().fi, y = qu.front().se; qu.pop();
for(int i = 0; i <= 7; ++i){
int a = x + dx[i], b = y + dy[i];
if(a >= 1 && a <= R && b >= 1 && b <= C && G[a][b] == '.' && d[a][b] == INF)
d[a][b] = d[x][y] + 1, qu.push(mp(a, b));
}
}
int res = -INF;
for(int i = 1; i <= R; ++i)
for(int j = 1; j <= C; ++j) if(d[i][j] != INF) res = max(res, d[i][j]);
cout << res << endl;
return 0;
}