流感传染(信息学奥赛一本通)

    科技2025-08-11  7

    题目描述 有一批易感人群住在网格状的宿舍区内,宿舍区为 n × n 的矩阵,每个格点为一个房间,房间里可能住人,也可能空着。

    在第一天,有些房间里的人得了流感,以后每天,得流感的人会使其邻居传染上流感(已经得病的不变),空房间不会传染。

    请输出第 m 天得流感的人数。

    输入格式 第一行一个数字 n,n 不超过100,表示有 n × n 的宿舍房间。 接下来的 n 行,每行 n 个字符,. 表示第一天该房间住着健康的人,# 表示该房间空着,@ 表示第一天该房间住着得流感的人。 接下来的一行是一个整数 m,m 不超过100。

    输出格式 输出第 m 天,得流感的人数。

    输入样例

    5 ....# .#.@. .#@.. #.... ..... 4

    输出样例 16


    题解 BFS:

    #include <iostream> #include <cstring> #include <queue> #define x first #define y second using namespace std; const int N = 110; typedef pair<int, int> PII; queue<PII> q; int n, m, cnt; char g[N][N]; int dist[N][N]; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; void bfs() { while(q.size()) { PII t = q.front(); q.pop(); if(dist[t.x][t.y] == m) return; for (int i = 0; i < 4; i ++) { int a = t.x + dx[i], b = t.y + dy[i]; if(a < 1 || a > n || b < 1 || b > n) continue; if(g[a][b] == '#' || dist[a][b] != -1) continue; cnt ++; q.push(make_pair(a, b)); dist[a][b] = dist[t.x][t.y] + 1; } } } int main() { cin >> n; memset(dist, -1, sizeof dist); for (int i = 1; i <= n; i ++) for (int j = 1; j <= n; j ++) { cin >> g[i][j]; if(g[i][j] == '@') { cnt ++; q.push(make_pair(i, j)); dist[i][j] = 1; } } cin >> m; bfs(); cout << cnt << endl; return 0; }

    错解:不知道哪里有问题😫

    #include <iostream> #include <cstring> #include <queue> #define x first #define y second using namespace std; const int N = 110; typedef pair<int, int> PII; queue<PII> q; int n, m, cnt; char g[N][N]; int dist[N][N]; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; int bfs() { while(q.size()) { PII t = q.front(); q.pop(); for (int i = 0; i < 4; i ++) { int a = t.x + dx[i], b = t.y + dy[i]; if(a < 1 || a > n || b < 1 || b > n) continue; if(g[a][b] == '#' || dist[a][b] != -1) continue; cnt ++; q.push(make_pair(a, b)); dist[a][b] = dist[t.x][t.y] + 1; if(dist[a][b] == m + 1) return cnt - 1; } } } int main() { cin >> n; memset(dist, -1, sizeof dist); for (int i = 1; i <= n; i ++) for (int j = 1; j <= n; j ++) { cin >> g[i][j]; if(g[i][j] == '@') { cnt ++; q.push(make_pair(i, j)); dist[i][j] = 1; } } cin >> m; cout << bfs() << endl; return 0; }
    Processed: 0.013, SQL: 8