MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / countSubIslands

Function countSubIslands

javascript/1905-count-sub-islands.js:1–35  ·  view source on GitHub ↗
(grid1, grid2)

Source from the content-addressed store, hash-verified

1var countSubIslands = function (grid1, grid2) {
2 let ROWS = grid1.length,
3 COLS = grid1[0].length;
4 let visit = new Set();
5
6 const dfs = function (r, c) {
7 let flatCoord = r * COLS + c;
8 if (
9 r < 0 ||
10 c < 0 ||
11 r == ROWS ||
12 c == COLS ||
13 grid2[r][c] == 0 ||
14 visit.has(flatCoord)
15 )
16 return true;
17
18 visit.add(flatCoord);
19 let res = true;
20 if (grid1[r][c] == 0) res = false;
21
22 res = dfs(r - 1, c) && res;
23 res = dfs(r + 1, c) && res;
24 res = dfs(r, c - 1) && res;
25 res = dfs(r, c + 1) && res;
26 return res;
27 };
28
29 let count = 0;
30 for (let r = 0; r < ROWS; r++)
31 for (let c = 0; c < COLS; c++)
32 if (grid2[r][c] && !visit.has(r * COLS + c) && dfs(r, c))
33 count += 1;
34 return count;
35};

Callers

nothing calls this directly

Calls 1

dfsFunction · 0.70

Tested by

no test coverage detected