1119. 【宽度优先搜索BFS】细胞
题目描述
一个矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:
4 10
0234500067
1034560500
2045600671
0000000089
则矩阵中一共有4个细胞。
样例输入
4 10
0234500067
1034560500
2045600671
0000000089
样例输出
4
数据范围限制
设矩阵的大小表示为n×m,则1<=n,m<=100。
#include <cstdio>
#include <iostream>
using namespace std;
int n, m, ans;
char a[105][105];
int h, t, q[10005][2];
int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
int main()
{
// freopen ("cell.in", "r", stdin);
// freopen ("cell.out", "w", stdout);
scanf ("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
cin >> a[i][j];
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (a[i][j] != '0')
{
ans++;
h = 0, t = 1;
q[t][0] = i;
q[t][1] = j;
a[i][j] = '0';
while (h < t)
{
h++;
int x = q[h][0];
int y = q[h][1];
for (int k = 0; k < 4; k++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && a[xx][yy] != '0')
{
t++;
q[t][0] = xx;
q[t][1] = yy;
a[xx][yy] = '0';
}
}
}
}
}
}
printf ("%d", ans);
return 0;
}
看了好几遍,到底哪错了,大佬求教QwQ