Skip to content

乳草的入侵

Original Link

思路

  • BFS
    • 难点一:处理地图坐标转换:
cpp
* 题目的地图坐标与二维数组坐标不对应;
* 则,第 `a` 排 `b` 列需要转换为 `mp[n - b][a - 1]`。
  • 难点二:记录消耗的周数:
cpp
* 由于 `BFS` 搜索不能直接记录当前层数;
* 则,考虑在新搜索到的点额外添加参数 `w`,来记录该点在第几周被感染;
* 最后用 `res` 维护最大的 `w` 即为答案。
  • 最后,搜索时要枚举八个方向,利用偏移量数组解决即可。

代码

cpp
#include <bits/stdc++.h>
using namespace std;

const int N = 210;

char mp[N][N];   // 存储地图
bool vis[N][N];  // 存储地图状态(是否可走)

int n, m, a, b, res;

int dx[] = {0, 0, 1, 1, -1, -1, 1, -1}, dy[] = {1, -1, 1, -1, 1, -1, 0, 0};  // 八个方向的偏移量

struct stu {
    int x, y, w;
};  // x, y 为横纵坐标,w 记录周数

int bfs(int l, int r, int w) {
    queue<stu> st;
    st.push({l, r, w});  // 起始点入队
    vis[l][r] = 1;  // 标记起始点已经走过

    while (!st.empty()) {  // 队列不空就不断搜索
        stu p = st.front(); st.pop();  // 取出队头
        res = max(res, p.w);  // 更新最大周数
        for (int i = 0; i < 8; i++) {  // 循环遍历偏移量数组枚举八个方向扩展搜索
            int nx = p.x + dx[i], ny = p.y + dy[i];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && mp[nx][ny] == '.') {  // 在边界内,且必须是 '.'
                vis[nx][ny] = 1;  // 标记为走过
                st.push({nx, ny, p.w + 1});  // 加入队尾后续搜索
            }
        }
    }
    return res;  // 返回答案
}

void solve() {
    cin >> m >> n >> a >> b;
    for (int i = 0; i < n; i++) cin >> mp[i];
    mp[n - b][a - 1] = 'M';
    cout << bfs(n - b, a - 1, 0) << endl;
}

int main() {
    solve();
    return 0;
}