洛谷.P1451 求细胞数量
题目描述
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。(1<=m,n<=100)?
输入输出格式
输入格式:
输入:整数m,n(m行,n列)
矩阵
输出格式:
输出:细胞的个数
输入输出样例
输入样例#1:
4 10
0234500067
1034560500
2045600671
0000000089
输出样例#1:
4
#include <cstdio>
#include <iostream>
#include<queue>
#include<cstring>
using namespace std;
int m, n, i, j;
int dir[4][2] = { -1, 0, 1, 0, 0, 1, 0, -1 };
int vis[110][110];
char s[110][110];
int ans;
struct node{
int x, y;
};
bool checkedge(int x, int y){
if (x<0 || x>=m || y<0 || y>=n || vis[x][y] == 1 || s[x][y]=='0')
return 1;
return 0;
}
void bfs(int x, int y){
ans++;
node now, next;
queue<node>q;
now.x = x;
now.y = y;
vis[x][y] = 1;
q.push(now);
while (!q.empty()){
int nx, ny;
now = q.front();
q.pop();
for (int k = 0; k < 4; k++){
nx = now.x + dir[k][0];
ny = now.y + dir[k][1];
if (checkedge(nx, ny))
continue;
next.x = nx;
next.y = ny;
q.push(next);
vis[nx][ny] = 1;
}
}
return;
}
int main(){
cin >> m >> n;
for (i = 0; i < m; i++)
cin >> s[i];
for (i = 0; i <m; i++){
for (j = 0; j < n; j++){
if (s[i][j] != '0' && vis[i][j] == 0)
bfs(i, j);
}
}
cout << ans << endl;
return 0;
}