-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find number of closed islands
69 lines (64 loc) · 1.83 KB
/
Find number of closed islands
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-->0)
{
String[] str = br.readLine().trim().split(" ");
int N = Integer.parseInt(str[0]);
int M = Integer.parseInt(str[1]);
int[][] matrix = new int[N][M];
for(int i=0; i<N; i++)
{
String[] s = br.readLine().trim().split(" ");
for(int j=0; j<M; j++)
matrix[i][j] = Integer.parseInt(s[j]);
}
Solution obj = new Solution();
System.out.println(obj.closedIslands(matrix, N, M));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution
{
static void help(int arr[][],int i,int j,int N,int M){
if(i<0 || j<0 || i==N || j==M || arr[i][j]==0)return;
arr[i][j]=0;
help(arr,i+1,j,N,M);
help(arr,i-1,j,N,M);
help(arr,i,j+1,N,M);
help(arr,i,j-1,N,M);
}
public int closedIslands(int[][] matrix, int N, int M)
{
// Code here
int ans=0;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(matrix[i][j]==1){
if(i==0 || j==0 || i==N-1 || j==M-1){
help(matrix,i,j,N,M);
}
}
}
}
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(matrix[i][j]==1){
ans++;
help(matrix,i,j,N,M);
}
}
}
return ans;
}
}