Skip to content

Commit 11cf061

Browse files
committed
solve: number of islands
1 parent 7640bd7 commit 11cf061

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* TC: O(ROW * COLUMN)
3+
* ์ฃผ์–ด์ง„ grid ๋ฐฐ์—ด ์ „์ฒด ์ˆœํšŒ + (์ตœ์•…์˜ ๊ฒฝ์šฐ queue์—์„œ grid ์ „์ฒด ์ˆœํšŒ)
4+
*
5+
* SC: O(ROW * COLUMN)
6+
* queue์—์„œ ์ตœ๋Œ€ grid๋งŒํผ ์ˆœํšŒ
7+
*
8+
* ROW: grid.length, COLUMN: grid[0].length
9+
*/
10+
11+
/**
12+
* @param {character[][]} grid
13+
* @return {number}
14+
*/
15+
var numIslands = function (grid) {
16+
const LAND = "1";
17+
const VISITED_LAND = "#";
18+
const ROW = grid.length;
19+
const COLUMN = grid[0].length;
20+
21+
// 1. ์ƒํ•˜์ขŒ์šฐ ๋ฐฉํ–ฅํ‚ค
22+
const DIRECTION = [
23+
{ r: 0, c: 1 },
24+
{ r: 1, c: 0 },
25+
{ r: 0, c: -1 },
26+
{ r: -1, c: 0 },
27+
];
28+
29+
let numberOfIslands = 0;
30+
31+
// 2. ์ „์ฒด ์ˆœํšŒํ•˜๋ฉด์„œ
32+
for (let row = 0; row < ROW; row++) {
33+
for (let column = 0; column < COLUMN; column++) {
34+
// 3. LAND๋ฅผ ๋ฐœ๊ฒฌํ•˜๋ฉด ๋ฐฉ๋ฌธํ•œ ์„ฌ์œผ๋กœ ํ‘œ์‹œ(bfs)ํ•˜๊ณ  ์„ฌ๊ฐฏ์ˆ˜ ๊ฐฑ์‹ 
35+
if (grid[row][column] === LAND) {
36+
bfs(row, column);
37+
numberOfIslands += 1;
38+
}
39+
}
40+
}
41+
42+
return numberOfIslands;
43+
44+
function bfs(startRow, startColumn) {
45+
// 4. ์‹œ์ž‘์ขŒํ‘œ queue์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธ ํ‘œ์‹œ
46+
const queue = [[startRow, startColumn]];
47+
grid[startRow][startColumn] = VISITED_LAND;
48+
49+
while (queue.length > 0) {
50+
const [row, column] = queue.shift();
51+
52+
// 5. ์ƒํ•˜์ขŒ์šฐ์˜ ์ขŒํ‘œ๋ฅผ ๊ฐ€์ง€๊ณ 
53+
for (const direction of DIRECTION) {
54+
const nextRow = row + direction.r;
55+
const nextColumn = column + direction.c;
56+
57+
// 6. ์œ ํšจํ•œ ์ขŒํ‘œ && ๋ฏธ๋ฐฉ๋ฌธ ์œก์ง€์ธ์ง€ ํ™•์ธ
58+
if (
59+
isValidPosition(nextRow, nextColumn) &&
60+
grid[nextRow][nextColumn] === LAND
61+
) {
62+
// 7. queue์— ์ถ”๊ฐ€ํ•˜๊ณ  ๋ฐฉ๋ฌธ ํ‘œ์‹œ
63+
grid[nextRow][nextColumn] = VISITED_LAND;
64+
queue.push([nextRow, nextColumn]);
65+
}
66+
}
67+
}
68+
}
69+
70+
// 8. ์ฃผ์–ด์ง„ 2์ฐจ์› ๋ฐฐ์—ด์˜ ์œ ํšจํ•œ ์ขŒํ‘œ์ธ์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜
71+
function isValidPosition(row, column) {
72+
if (row < 0 || ROW <= row) {
73+
return false;
74+
}
75+
if (column < 0 || COLUMN <= column) {
76+
return false;
77+
}
78+
return true;
79+
}
80+
};

0 commit comments

Comments
ย (0)