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

题目描述
有一批易感人群住在网格状的宿舍区内,宿舍区为 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;	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值