MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / countSubIslands

Method countSubIslands

java/1905-count-sub-islands.java:6–41  ·  view source on GitHub ↗
(final int[][] grid1, final int[][] grid2)

Source from the content-addressed store, hash-verified

4 }
5
6 public int countSubIslands(final int[][] grid1, final int[][] grid2) {
7 final int ROWS = grid1.length, COLS = grid1[0].length;
8 final Set<Integer> visit = new HashSet<>();
9
10 final RecursiveBiFunction<Integer, Integer, Boolean> dfs = new RecursiveBiFunction<>();
11 dfs.func = (r, c) -> {
12 int flatCoord = r*COLS + c;
13 if(
14 r < 0
15 || c < 0
16 || r == ROWS
17 || c == COLS
18 || grid2[r][c] == 0
19 || visit.contains(flatCoord)
20 )
21 return true;
22
23 visit.add(flatCoord);
24 boolean res = true;
25 if(grid1[r][c] == 0)
26 res = false;
27
28 res = dfs.func.apply(r - 1, c) && res;
29 res = dfs.func.apply(r + 1, c) && res;
30 res = dfs.func.apply(r, c - 1) && res;
31 res = dfs.func.apply(r, c + 1) && res;
32 return res;
33 };
34
35 int count = 0;
36 for(int r = 0; r < ROWS; r++)
37 for(int c = 0; c < COLS; c++)
38 if(grid2[r][c] != 0 && !visit.contains(r*COLS + c) && dfs.func.apply(r, c))
39 count += 1;
40 return count;
41 }
42}

Callers

nothing calls this directly

Calls 2

containsMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected