nyoj27-水池数目(并查集||暴力递归)

1.用并查集将相邻水池union(求连通分支!)

#include
#define Max 10005
int father[Max];int map[101][101];
void make_set(int n)
{
    for(int i=1;i<=n;i++){
        father[i]=i;
    }
}   
int find_set(int n)
{
    if(father[n]!=n)
    father[n]=find_set(father[n]);
    return father[n];
}
void union_set(int a,int b)
{
    int x=find_set(a);
    int y=find_set(b);
    if(x!=y)
    father[x]=y;
}
int main()
{
    int T,m,n,i,j;
    scanf("%d",&T);
    while(T--)
    {

        scanf("%d%d",&m,&n);make_set(m*n);
        for(i=1;i<=m;i++)
        for(j=1;j<=n;j++){
            int t;
            scanf("%d",&t);map[i][j]=t;
            if(t==1){
                int x,y;
                x=i-1;y=j;
                if(x>=1&&map[x][y]!=0)
                {
                    union_set((x-1)*n+y,(i-1)*n+j);
                }

                x=i;y=j-1;
                if(y>=1&&map[x][y]!=0)
                {
                    union_set((x-1)*n+y,(i-1)*n+j);
                }
            }
            else
            father[(i-1)*n+j]=-1;
        }
        int count=0;
        for(i=1;i<=m*n;i++){
            if(find_set(i)==i)
            count++;
        }
        printf("%d\n",count);   
    }
    return 0;
}

2.向四周递归(访问过置0即可!)

#include
int map[102][102];
void dfs(int i,int j)
{
    if(map[i][j-1]){map[i][j-1]=0;dfs(i,j-1);}
    if(map[i][j+1]){map[i][j+1]=0;dfs(i,j+1);}
    if(map[i-1][j]){map[i-1][j]=0;dfs(i-1,j);}
    if(map[i+1][j]){map[i+1][j]=0;dfs(i+1,j);}

}     
int main()
{
    int T,m,n,i,j;
    scanf("%d",&T);
    while(T--)
    {
        int count=0;
        scanf("%d%d",&m,&n);
        for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        scanf("%d",&map[i][j]);
        for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        if(map[i][j]==1){
            count++;map[i][j]=0;dfs(i,j);
        }
        printf("%d\n",count);
    }
    return 0;
} 

你可能感兴趣的:(OJ与算法,nyoj)