Friday, 21 February 2014

Number of islands

All connected 1's (directly or diagonally) considered as one island.
see the test cases for more description.



#include<iostream>
#include<stdio.h>

int a[1000][1000];


void fun(int i,int j,int n){
if(i<0 || j<0 ||i>n-1 || j>n-1)
return;

if(a[i][j]==0)return;

a[i][j]=0;
fun(i-1,j-1,n);
fun(i-1,j,n);
fun(i,j-1,n);
fun(i-1,j+1,n);
fun(i+1,j-1,n);
fun(i+1,j,n);
fun(i,j+1,n);
fun(i+1,j+1,n);

}

using namespace std;

int main(){

int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);

for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&a[i][j]);

int cnt=0;

for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
    if(a[i][j]==1 )  {
    cnt++;
    fun(i,j,n);
    }
    }
    }
printf("%d\n",cnt);

}
}


Sample Input: 
2


1 0 0 1 
0 0 0 0 
0 1 1 0 
1 0 0 1 


0 0 1 0 0 1 0 0 
1 0 0 0 0 0 0 1 
0 0 1 0 0 1 0 1 
0 1 0 0 0 1 0 0 
1 0 0 0 0 0 0 0 
0 0 1 1 0 1 1 0 
1 0 1 1 0 1 1 0 
0 0 0 0 0 0 0 0 

Sample Output: 

9

No comments:

Post a Comment