Explanation:
Connected set can be defined as group of cell(s) which has 1 mentioned on it and have at least one other cell in that set with which they share the neighbor relationship. A cell with 1 in it and no surrounding neighbor having 1 in it can be considered as a set with one cell in it. Neighbors can be defined as all the cells adjacent to the given cell in 8 possible directions ( i.e N , W , E , S , NE , NW , SE , SW direction ). A cell is not a neighbor of itself.
/*CODE*/
#include<stdio.h>
#define SIZE 1010
void disable_connected(int i, int j);
int matrix[SIZE][SIZE]={0};
main()
{
int t,size,i,j,k,num_connected=0;
scanf("%d",&t);
while(t)
{
t--;
num_connected = 0;
scanf("%d",&size);
for(i=0;i<=size+1;i++)
{
matrix[0][i] = matrix[size+1][i]= matrix[i][0] = matrix [i][size+1] = 0;
}
for(i=1;i<=size;i++)
{
for(j=1;j<=size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
for(i=1;i<=size;i++)
{
for(j=0;j<=size;j++)
{
if(matrix[i][j] == 1)
{
disable_connected(i,j);
num_connected++;
}
}
}
printf("%d\n",num_connected);
}
return 0;
}
void disable_connected(int i, int j)
{
int p,q;
matrix[i][j] = 2;
for(p=i-1;p<=i+1;p++)
{
for(q=j-1;q<=j+1;q++)
{
if(matrix[p][q] == 1)
{
matrix[p][q] =2;
disable_connected(p,q);
}
}
}
return ;
}
No comments:
Post a Comment