Skip to content

Commit f8fa89a

Browse files
committed
3. Number of Islands
1 parent d819cc5 commit f8fa89a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

number-of-islands/sunjae95.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* hash table + two pointer
5+
*
6+
* n = length of grid
7+
* k = length of grid[index]
8+
* time complexity: O(n * k)
9+
* space complexity: O(n * k)
10+
*/
11+
var numIslands = function (grid) {
12+
let answer = 0;
13+
const visited = Array.from({ length: grid.length }, (_, i) =>
14+
Array.from({ length: grid[i].length }, () => false)
15+
);
16+
17+
const dfs = (r, c) => {
18+
const dr = [0, 1, 0, -1];
19+
const dc = [1, 0, -1, 0];
20+
21+
for (let i = 0; i < 4; i++) {
22+
const nextR = r + dr[i];
23+
const nextC = c + dc[i];
24+
25+
if (
26+
nextR >= 0 &&
27+
nextR < grid.length &&
28+
nextC >= 0 &&
29+
nextC < grid[r].length &&
30+
grid[nextR][nextC] == 1 &&
31+
!visited[nextR][nextC]
32+
) {
33+
visited[nextR][nextC] = true;
34+
dfs(nextR, nextC);
35+
}
36+
}
37+
};
38+
39+
for (let row = 0; row < grid.length; row++) {
40+
for (let column = 0; column < grid[row].length; column++) {
41+
if (grid[row][column] == 1 && !visited[row][column]) {
42+
visited[row][column] = true;
43+
answer++;
44+
dfs(row, column);
45+
}
46+
}
47+
}
48+
return answer;
49+
};

0 commit comments

Comments
 (0)