File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ The basic idea is to iterate through the boundary
3
+ If we encounter any island i.e. 1 then we will run DFS
4
+ And update all those islands as 2
5
+
6
+ Then check for the number of 1s remaining in the board
7
+ Since those are the ones that have not been visited and return
8
+ */
9
+
10
+ class Solution {
11
+ public int count (int [][]board ){
12
+ int c = 0 ;
13
+ for (int i =0 ; i <board .length ; i ++){
14
+ for (int j =0 ; j <board [0 ].length ; j ++){
15
+ if (board [i ][j ] == 1 ){
16
+ c ++;
17
+ }
18
+ }
19
+ }
20
+ return c ;
21
+ }
22
+ public void dfs (int r , int c , int [][] board ){
23
+ if (r <0 || c <0 || r >board .length -1 || c >board [0 ].length -1 || board [r ][c ] != 1 ) return ;
24
+
25
+ board [r ][c ] = 2 ;
26
+
27
+ dfs (r +1 , c , board );
28
+ dfs (r -1 , c , board );
29
+ dfs (r , c +1 , board );
30
+ dfs (r , c -1 , board );
31
+ }
32
+ public int numEnclaves (int [][] board ) {
33
+ int n =board .length , m =board [0 ].length ;
34
+
35
+ for (int i =0 ; i <n ; i ++){
36
+ if (board [i ][0 ] == 1 ) dfs (i , 0 , board );
37
+ if (board [i ][m -1 ] == 1 ) dfs (i , m -1 , board );
38
+ }
39
+
40
+ for (int i =1 ; i <m -1 ; i ++){
41
+ if (board [0 ][i ] == 1 ) dfs (0 , i , board );
42
+ if (board [n -1 ][i ] == 1 ) dfs (n -1 , i , board );
43
+ }
44
+ return count (board );
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments