Skip to content

Commit 22ae50f

Browse files
committed
number-of-islands solution
1 parent c5aadf3 commit 22ae50f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

number-of-islands/lhc0506.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
var numIslands = function(grid) {
6+
const m = grid.length;
7+
const n = grid[0].length;
8+
const visited = Array.from(new Array(m), () => new Array(n).fill(false));
9+
const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
10+
11+
let islandCount = 0;
12+
13+
for (let i = 0; i < m; i++) {
14+
for (let j = 0; j < n; j++) {
15+
if (grid[i][j] === '1' && !visited[i][j]) {
16+
const queue = [[i, j]];
17+
visited[i][j] = true;
18+
19+
while (queue.length) {
20+
const [y, x] = queue.shift();
21+
22+
for (const [dy, dx] of directions) {
23+
const newY = y + dy;
24+
const newX = x + dx;
25+
26+
if (newY >= 0 && newY < m && newX >= 0 && newX < n && grid[newY][newX] === '1' && !visited[newY][newX]) {
27+
visited[newY][newX] = true;
28+
queue.push([newY, newX]);
29+
}
30+
}
31+
}
32+
33+
islandCount += 1;
34+
}
35+
}
36+
}
37+
38+
return islandCount;
39+
};
40+
41+
// 시간복잡도: O(m * n)
42+
// 공간복잡도: O(m * n)

0 commit comments

Comments
 (0)