P1451 求細(xì)胞數(shù)量
#include<bits/stdc++.h>
using namespace std;
int n,m;
char a[101][101];//
int ans=0;
void shensou(int x,int y) {
? ?//邊界條件判斷直接返回
? ?if(x<1||y<1||x>n||y>m) {//網(wǎng)格問題一定要有邊界條件
? ? ? ?return ;
? ?}
? ?//以下是四個(gè)點(diǎn)的判斷
? ?//不為零是變?yōu)榱愕牟僮魇诸愃朴趘isited數(shù)組變?yōu)榱銟?biāo)記為已占領(lǐng)不為零說明可搜索
? ?//只要不是0都變成0,然后繼續(xù)搜索
? ?if(a[x][y+1]!='0') {
? ? ? ?a[x][y+1]='0';
? ? ? ?shensou(x,y+1);
? ?}
? ?if(a[x][y-1]!='0') {
? ? ? ?a[x][y-1]='0';
? ? ? ?shensou(x,y-1);
? ?}
? ?if(a[x+1][y]!='0') {
? ? ? ?a[x+1][y]='0';
? ? ? ?shensou(x+1,y);
? ?}
? ?if(a[x-1][y]!='0') {
? ? ? ?a[x-1][y]='0';
? ? ? ?shensou(x-1,y);
? ?}
}
int main() {
? ?scanf("%d%d",&n,&m);
? ?for(int i=1; i<=n; i++) {
? ? ? ?for(int j=1; j<=m; j++) {
? ? ? ? ? ?cin>>a[i][j];
? ? ? ? ? ?//用字符數(shù)組輸入,因?yàn)闆]有空格
? ? ? ?}
? ?}
? ?for(int i=1; i<=n; i++) {
? ? ? ?for(int j=1; j<=m; j++) {
? ? ? ? ? ?if(a[i][j]!='0') {
? ? ? ? ? ? ? ?a[i][j]=0;//不是0就變成零
? ? ? ? ? ? ? ?ans++;
? ? ? ? ? ? ? ?shensou(i,j);
? ? ? ? ? ? ? ?//目的是將所有這個(gè)細(xì)胞中的元素清零
? ? ? ? ? ? ? ?//這樣就可以直接找下一個(gè)細(xì)胞的某個(gè)元素
? ? ? ? ? ?}
? ? ? ?}
? ?}
? ?printf("%d",ans);
? ?return 0;
}
