Skip to content

Commit 6b6b880

Browse files
committed
Added numIslands solution
1 parent 26069de commit 6b6b880

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

number-of-islands/nhistory.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var numIslands = function (grid) {
2+
// Declare row and column length
3+
const m = grid.length,
4+
n = grid[0].length;
5+
let numIslands = 0;
6+
7+
// Available directions for depth-first search
8+
const dir = [
9+
[0, 1],
10+
[1, 0],
11+
[0, -1],
12+
[-1, 0],
13+
];
14+
15+
// Function to depth-first search inside of grid
16+
const dfs = (i, j) => {
17+
grid[i][j] = "2";
18+
19+
let x, y;
20+
for (d of dir) {
21+
x = i + d[0];
22+
y = j + d[1];
23+
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] === "1") {
24+
dfs(x, y);
25+
}
26+
}
27+
return;
28+
};
29+
30+
for (let i = 0; i < m; i++) {
31+
for (let j = 0; j < n; j++) {
32+
if (grid[i][j] === "1") {
33+
dfs(i, j);
34+
numIslands++;
35+
}
36+
}
37+
}
38+
return numIslands;
39+
};
40+
41+
// TC: O(m*n)
42+
// SC: O(m*n)

0 commit comments

Comments
 (0)