【小韦同学@神犇营-my1089-细胞】
题目:
描述
一矩形阵列由数字 0 到 9 组成,数字 1 到 9 代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:阵列
有4个细胞。
输入
第一行为矩阵的行 n 和列 m;
下面为一个 n×m 的矩阵。
输出
细胞个数。
输入样例1
4 10
0234500067
1034560500
2045600671
0000000089
输出样例1
4
题解:
/*********************************************************************
* 题目:神犇营-my1089-细胞
* 作者:小韦同学
* 邮箱:weichangying_wcy@163.com
* 题解:
思路:
就是求图的连通块,这里用的是 BFS。
*********************************************************************/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
char matrix[N][N];
int n, m;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool vis[N][N];
struct node {
int x, y;
node(int xx, int yy) {
x = xx;
y = yy;
}
};
bool in(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < m;
}
bool check(int x, int y) {
char c = matrix[x][y];
if (c == '0') return false;
else return true;
}
void bfs(int x, int y) {
queue<node> q;
q.push(node(x, y));
vis[x][y] = true;
while (!q.empty()) {
node now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = now.x + dir[i][0];
int ty = now.y + dir[i][1];
if (in(tx, ty) && !inq[tx][ty] && check(tx, ty) && !vis[tx][ty]) {
q.push(node(tx, ty));
vis[tx][ty] = true;
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!vis[i][j] && check(i, j)) {
bfs(i, j);
cnt++;
}
}
}
cout << cnt;
return 0;
}
我是小韦同学,企者不立,跨者不行,每天进步一点点。
欢迎大家多多交流,如果发现有错误,请多指正。有疑问的同学也可以留言评论或者发邮件。
邮箱:weichangying_wcy@163.com