Skip to content

Commit d2f737e

Browse files
committed
number-of-islands solution
1 parent 5cfe8c4 commit d2f737e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

โ€Žnumber-of-islands/jdy8739.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
var numIslands = function (grid) {
6+
const sink = (row, col) => {
7+
grid[row][col] = '0';
8+
9+
const neighbor = [
10+
[row + 1, col], [row, col + 1], [row - 1, col], [row, col - 1]
11+
].filter(([y, x]) => {
12+
return y >= 0 && x >= 0 && y < grid.length && x < grid[0].length;
13+
}).filter(([y, x]) => {
14+
return grid[y][x] === '1';
15+
});
16+
17+
neighbor.forEach(([y, x]) => {
18+
const el = grid[y][x];
19+
20+
if (el === '1') {
21+
sink(y, x);
22+
}
23+
})
24+
}
25+
26+
let count = 0;
27+
28+
for (let i = 0; i < grid.length; i++) {
29+
for (let j = 0; j < grid[0].length; j++) {
30+
31+
if (grid[i][j] === '1') {
32+
count++;
33+
sink(i, j);
34+
}
35+
}
36+
}
37+
38+
return count;
39+
};
40+
41+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(2 * m * n) -> m * n ๋งŒํผ ๋ฐ˜๋ณต + ์žฌ๊ท€์ ์œผ๋กœ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š” ์…€์˜ ์ˆ˜๋Š” ์ด m * n ๊ฐœ
42+
// ๊ณต๊ฐ„๋ณต์žก๋„ O(1) -> ์ž…๋ ฅ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
43+

0 commit comments

Comments
ย (0)