Skip to content

Commit 0563971

Browse files
committed
Add number-of-islands solution
1 parent 4218a1b commit 0563971

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

number-of-islands/Jeehay28.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
6+
// 🌻
7+
// Time Complexity: O(m * n), where M is the number of rows and N is the number of columns in the grid.
8+
// Space Complexity: O(k), where k is the size of the largest island (k <= m * n)
9+
10+
// The space complexity is determined by the depth of the recursive stack used by the sink function.
11+
// In the worst-case scenario, where the entire grid is filled with "1"s (a single large island),
12+
// the depth of recursion could go up to O(m * n).
13+
14+
var numIslands = function (grid) {
15+
// depth-first search (DFS) that potentially visits every connected cell in the current island
16+
const sink = (row, col) => {
17+
grid[row][col] = "0";
18+
19+
const adjacent = [
20+
[row - 1, col], // up
21+
[row + 1, col], // down
22+
[row, col - 1], // left
23+
[row, col + 1], // right
24+
];
25+
26+
for ([r, c] of adjacent) {
27+
if (r >= 0 && r < grid.length && c >= 0 && c < grid[r].length) {
28+
if (grid[r][c] === "1") {
29+
sink(r, c);
30+
}
31+
}
32+
}
33+
};
34+
35+
let cnt = 0;
36+
37+
for (let i = 0; i < grid.length; i++) {
38+
for (let j = 0; j < grid[0].length; j++) {
39+
if (grid[i][j] === "1") {
40+
cnt += 1;
41+
sink(i, j);
42+
}
43+
}
44+
}
45+
46+
return cnt;
47+
};
48+
49+
50+

0 commit comments

Comments
 (0)