View Code of Problem 62

#include<stdio.h>
#include<math.h>
#include<string.h>
 /*借鉴前辈*/ 
char ch[120][120];
 
void same(int i,int j,int n, int k)
{
	if(i<0||j<0||i>=n||j>=k)//如果越界了就返回上一层 
	{
		return;
	}
	if(ch[i][j]=='0')//该位置没有养就退出 
	{
		return;
	}
	ch[i][j]='0';//记住判断完之后讲原来的位置置0,以避免重复计算 
	same(i-1,j,n,k);
	same(i+1,j,n,k);
	same(i,j+1,n,k);
	same(i,j-1,n,k);
	same(i-1,j-1,n,k);
	same(i-1,j+1,n,k);
	same(i+1,j+1,n,k);
	same(i+1,j-1,n,k);
	return;
}
 
int main(){
    int n,k;
    int count;
    while(scanf("%d %d",&n,&k)){
        if(n == 0 && k == 0)
            break;
        count= 0;
        for(int i = 0;i < n;i++){
                scanf("%s",ch[i]);//输入字符串 
        }
        
        for(int i = 0;i < n;i++){
            for(int j = 0;j < k;j++){
                if(ch[i][j] == '1'){
                    same(i,j,n,k);
                    count++;   
                }
            }
        }
        printf("%d\n",count);
        
    }
    return 0;
}

Double click to view unformatted code.


Back to problem 62