目录

1191流感传染-BFS

1191:流感传染–BFS

题目

https://i-blog.csdnimg.cn/direct/5b77050d6c204cbbac654f8a504e2252.png

解析

在同一天对一个病原体进行处理时,如果直接更改数组,将直接影响到后续的遍历

方法一:那么我们可以定义一个数组用来 存储坐标vectoir<pair<int,int>> ,遍历完所有坐标后,在统一更改感染。

for (auto &p : toInfect) {
            a[p.first][p.second] = '@';
        }

方法二:下述的BFS代码中利用结构体存储该天的感染人的坐标,再while 遍历完所有的坐标

代码

#include <iostream>
#include <vector>
using namespace std;

int n, m, cnt;
char a[110][110];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};

void check() {
    for (int d = 0; d < m - 1; d++) { // 处理m-1次传播
        vector<pair<int, int> > toInfect;//记录今天会被感染人的坐标
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (a[i][j] == '@') {
                    for (int k = 0; k < 4; k++) {
                        int nx = i + dx[k], ny = j + dy[k];
                        if (nx >= 0 && nx < n && ny >= 0 && ny < n && a[nx][ny] == '.') {
                            toInfect.push_back({nx, ny});
                        }
                    }
                }
            }
        }
        // 统一更新感染
        for (auto &p : toInfect) {
            a[p.first][p.second] = '@';
        }
    }
}

int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> a[i][j];
        }
    }
    cin >> m;
    check();
    cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j] == '@') cnt++;
        }
    }
    cout << cnt << endl;
    return 0;
}

BFS代码

#include <iostream>
#include <queue>
using namespace std;

struct Node {
    int x, y, day;  // 坐标和感染时间
};

int n, m;
char grid[110][110];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};

int bfs() {
    queue<Node> q;
    // 初始化队列:记录所有初始感染者
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[i][j] == '@') {
                q.push({i, j, 1});
            }
        }
    }

    while (!q.empty()) {
        Node node = q.front();
        q.pop();
        if (node.day >= m) continue;  // 超过天数则不传播

        for (int k = 0; k < 4; k++) {
            int nx = node.x + dx[k], ny = node.y + dy[k];
            if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
                // 仅感染健康的人
                if (grid[nx][ny] == '.') {
                    grid[nx][ny] = '@';
                    q.push({nx, ny, node.day + 1});
                }
            }
        }
    }

    // 统计结果
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[nx][ny] == '@') cnt++;
        }
    }
    return cnt;
}

int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> grid[i][j];
        }
    }
    cin >> m;
    cout << bfs() << endl;
    return 0;
}