Number of Closed Islands LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} grid
3
* @return {number}
4
*/
5
var closedIsland = function (grid) {
6
let rows = grid.length;
7
let cols = grid[0].length;
8
let islandCount = 0; // Initial island count
9

10
// For Quick Response
11
if (rows <= 2 || cols <= 2) return islandCount;
12

13
for (let i = 0; i <= rows - 1; i++) {
14
for (let j = 0; j <= cols - 1; j++) {
15
/*
16
If land was found on the border, it can never be enclosed by water.
17
So, mark the all the adjacent land across grid as visited.
18
*/
19
if (
20
grid[i][j] === 0 &&
21
(i == 0 || j == 0 || i == rows - 1 || j == cols - 1)
22
) {
23
dfs(i, j);
24
}
25
}
26
}
27

28
// If land is found, increase the count and walk around land(adjacent indexes) to mark them as visited.
29
for (let i = 1; i <= rows - 1; i++) {
30
for (let j = 1; j <= cols - 1; j++) {
31
if (grid[i][j] === 0) {
32
islandCount++;
33
dfs(i, j);
34
}
35
}
36
}
37

38
// To walk around land and mark it as visited
39
function dfs(x, y) {
40
if (x < 0 || y < 0 || x >= rows || y >= cols) return;
41
if (grid[x][y] !== 0) return;
42

43
grid[x][y] = 2;
44

45
dfs(x + 1, y);
46
dfs(x, y + 1);
47
dfs(x - 1, y);
48
dfs(x, y - 1);
49
}
50

51
return islandCount;
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0