信息学奥赛一本通 1329:【例8.2】细胞

题目

【题目描述】

一矩形阵列由数字00到99组成,数字11到99代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:

阵列

4 10
0234500067
1034560500
2045600671
0000000089

有44个细胞。

【输入】

第一行为矩阵的行n�和列m�;

下面为一个n×m�×�的矩阵。

【输出】

细胞个数。

【输入样例】

4 10
0234500067
1034560500
2045600671
0000000089

【输出样例】

4

代码

#include<iostream>
#include<queue>
using namespace std;
const int N = 145;
char g[N][N];
int n, m;
// Flood Fill
struct node {
	int x, y;
	node(int x, int y) : x(x), y(y) {}
};
queue<node> q;
void push(int x, int y) {
	q.emplace(x, y);
	g[x][y] = '0';
}
bool is_valid(int x, int y) {
	return x >= 0 && x < n&& y >= 0 && y < m&& g[x][y] != '0';
}
void flood_fill(int x, int y) {
	push(x, y);
	while (q.size()) {
		node t = q.front();
		q.pop();
		node points[] = { node(t.x - 1,t.y),node(t.x + 1,t.y),node(t.x,t.y - 1),node(t.x,t.y + 1) };
		for (int i = 0; i < 4; i++) {
			node p = points[i];
			if (is_valid(p.x, p.y)) push(p.x, p.y);
		}
	}
}
int main() {
	int ans = 0;
	cin >> n >> m;
	for (int i = 0; i < n; i++) cin >> g[i];
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			if (g[i][j] != '0') {
				flood_fill(i, j);
				ans++;
			}
	cout << ans << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值