题目
【题目描述】
一矩形阵列由数字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;
}