Number of islands
All connected 1's (directly or diagonally) considered as one island.
see the test cases for more description.
see the test cases for more description.
#include<iostream>
#include<stdio.h>
#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
4
1 0 0 1
0 0 0 0
0 1 1 0
1 0 0 1
8
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:
3
9
4
1 0 0 1
0 0 0 0
0 1 1 0
1 0 0 1
8
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:
3
9
No comments:
Post a Comment