Description
一矩形阵列由数字
0
0
0到
9
9
9组成,数字
1
1
1到
9
9
9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:阵列
0234500067
1034560500
2045600671
0000000089
有4个细胞。
Input
输入共
m
+
1
m+1
m+1行第一行有两个数据,分别表示总行数和总列数以下的
m
m
m行,每行有
n
n
n个
0
−
9
0-9
0−9之间的数
Output
细胞个数
Sample Input
4
0234500067
1034560500
2045600671
0000000089
Sample Output
4
解题思路
本题很明显是
B
F
S
BFS
BFS(广搜)。广搜,出门右拐百度一下
广搜板子.
但判断新的细胞比较麻烦,所以我枚举了每个点(非零),从一个点去扩展一个细胞,找过的用0标记。。。
代码
#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
int a[1000][1000],st[1000][2],h,t,ans=0;//st[][1]记录横坐标,st[][2]表示纵坐标
const int dx[5]={0,1,0,0,-1};
const int dy[5]={0,0,1,-1,0};
bool check(int x,int y){
if(x>0&&x<=n&&y>0&&y<=m&&a[x][y])//是否超界及有没有走过
return 1;
else
return 0;
}
void bfs(int x,int y){
h=0; t=1;
st[1][1]=x;
st[1][2]=y;
do
{
h++;
for(int i=1;i<=4;i++)
{
if(check(st[h][1]+dx[i],st[h][2]+dy[i]))
{
t++;
st[t][1]=st[h][1]+dx[i];
st[t][2]=st[h][2]+dy[i];
a[st[h][1]+dx[i]][st[h][2]+dy[i]]=0;//找到过的标记
}
}
}while(h<=t);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
string s;
cin>>s;//字符输入别忘了
for(int j=0;j<m;j++)
a[i][j+1]=s[j]-48;
}
for(int i=1;i<=n;i++)//枚举每个点
{
for(int j=1;j<=m;j++)
{
if(a[i][j])//判断那个点是否可走
{
bfs(i,j);
ans++;
}
}
}
cout<<ans;
}