dfs

链接:https://ac.nowcoder.com/acm/contest/558/J
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

小猫在研究网格图。
小猫在研究联通性。
给定一张N×M的网格图,只含字符0和1,问1形成的联通块有多少个。
两个1是联通的,当且仅当其中一个位于另一个的上、下、左、右四个方向之一。

输入描述:

第一行一个正整数T,表示数据组数。

每组数据的第一行两个正整数N,M,表示矩阵的长和宽。

接下来N行,每行M个字符0或1。

输出描述:

T行,每行一个正整数,表示每组数据的答案。
示例1

输入

复制
2
3 5
10101
01110
10101
3 3
111
010
111

输出

复制
5
1

备注:

1≤T,N,M≤50
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn=55;

int m,n,t,cnt;
int map[maxn][maxn],book[maxn][maxn];
char str[maxn];
int sum,maxx;
int nex[][2]={{1,0},{0,1},{-1,0},{0,-1}};

void dfs(int x,int y){
    //printf("!!  ");
    for(int i=0;i<4;i++){
        int tx=x+nex[i][0];
        int ty=y+nex[i][1];
        if(tx<1||ty<1||ty>m||tx>n){
            continue;
        }else if(map[tx][ty]==1&&book[tx][ty]==0){
            book[tx][ty]=cnt;
            dfs(tx,ty);
        }
    }
}

int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        memset(book,0,sizeof(book));
        getchar();
        for(int i=1;i<=n;i++){
            scanf("%s",str);
            for(int j=0;j<m;j++){
                map[i][j+1]=str[j]-'0';
            }
        }
        //printf("
");
    
        maxx=-0x3f3f3f3f;
        cnt=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                //memset(book,0,sizeof(book));
                if(map[i][j]==1&&book[i][j]==0){
                    cnt++;
                    book[i][j]=cnt;
                    dfs(i,j);
                }
                
            }
        }
        printf("%d
",cnt);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/qqshiacm/p/10705736.html