Connected block problem

Judge that a binary array has several connected blocks, and eight fields are connected.

1. Two arrays, one storage element and one storage id of connected block. All the initial IDs are 0;
2. Traverse all elements. When the element is' @ 'and the id is 0 (indicating that it is not accessed), assign its id to the current id (id+1 of one more connected block);
3. Then search all the elements connected with the current element from the location dfs of the current element to make its connected element id equal to the current id. the following conditions need to be met:
(1) . subscript does not cross boundary
(2) . element is' @ 'and id is 0;
4. After traversal, all elements with the same id represent connectivity. The element with the largest id represents a total of several connected blocks.
Code:

#include <stdio.h>
int count=0;
char arr[5][8]={"***@****",
                "***@@***",
                "**@***@*",
                "*****@**",
                "*@**@@**"};
int id[5][8];
int count_id=0;
void DFS(int x,int y)
{
    int i,j;
    for(i=-1;i<=1;i++)
    {
        for(j=-1;j<=1;j++)
        {
            int xx=x+i;
            int yy=y+j;
            if(xx!=x || yy!=y)
            {
                if(xx>=0 && xx<5 && yy>=0 && yy<8)
                {
                    if( id[xx][yy]==0 && arr[xx][yy]=='@')
                    {
                        id[xx][yy]=id[x][y];
                        DFS(xx,yy);
                    }
                }
            }
        }
    }

}
int main()
{
    int i,j;
    for(i=0;i<5;i++)
    {
        for(j=0;j<8;j++)
        {
            printf("%c ",arr[i][j]);
        }
        printf("\n");
    }
    for(i=0;i<5;i++)
    {
        for(j=0;j<8;j++)
        {
            if(arr[i][j]=='@' && id[i][j]==0)
            {
                id[i][j]=++count_id;
                DFS(i,j);
            }
        }
    }
    for(i=0;i<5;i++)
    {
        for(j=0;j<8;j++)
        {
            printf("%d ",id[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Posted by kr9091 on Sun, 05 Apr 2020 02:28:52 -0700