Skip to content

Commit e6e48af

Browse files
committed
add solution : 200. Number of Islands
1 parent 5e35f9c commit e6e48af

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

โ€Žnumber-of-islands/mmyeon.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
*@link https://leetcode.com/problems/number-of-islands/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - ์„ฌ์˜ ์‹œ์ž‘์ ์—์„œ ๋๊นŒ์ง€ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๋ฏ€๋กœ DFS ์‚ฌ์šฉ
6+
* - ๋ฐฉ๋ฌธํ•œ ์„ฌ์€ ์ค‘๋ณต ํƒ์ƒ‰ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋ฐฉ๋ฌธ ํ›„ ๊ฐ’ ๋ณ€๊ฒฝ ์ฒ˜๋ฆฌ
7+
*
8+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(m * n)
9+
* - 2์ฐจ์› ๋ฐฐ์—ด ์ „์ฒด๋ฅผ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(m * n)
10+
*
11+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(m * n)
12+
* - DFS ํ˜ธ์ถœ ์Šคํƒ ์ตœ๋Œ€ ๊นŠ์ด๊ฐ€ m * n ๋งŒํผ ์Œ“์ผ ์ˆ˜ ์žˆ๋‹ค.
13+
*/
14+
15+
function numIslands(grid: string[][]): number {
16+
let count = 0;
17+
const rows = grid.length;
18+
const cols = grid[0].length;
19+
20+
// ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰ ๋ฐฉํ–ฅ ๋ฐฐ์—ด
21+
const directions = [
22+
[0, -1],
23+
[0, 1],
24+
[-1, 0],
25+
[1, 0],
26+
];
27+
28+
// ํ˜„์žฌ ์œ„์น˜์—์„œ ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ์„ฌ ํƒ์ƒ‰
29+
const dfs = (row: number, col: number) => {
30+
// ์ข…๋ฃŒ ์กฐ๊ฑด : ๋ฒ”์œ„ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜, ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๊ฒฝ์šฐ
31+
if (
32+
row < 0 ||
33+
row >= rows ||
34+
col < 0 ||
35+
col >= cols ||
36+
grid[row][col] === "0"
37+
)
38+
return;
39+
40+
// ํ˜„์žฌ ์œ„์น˜ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
41+
grid[row][col] = "0";
42+
43+
// ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰
44+
for (const [x, y] of directions) {
45+
dfs(row + x, col + y);
46+
}
47+
};
48+
49+
for (let row = 0; row < rows; row++) {
50+
for (let col = 0; col < cols; col++) {
51+
// ์„ฌ์˜ ์‹œ์ž‘์ ์ธ ๊ฒฝ์šฐ
52+
if (grid[row][col] === "1") {
53+
count++;
54+
dfs(row, col);
55+
}
56+
}
57+
}
58+
59+
return count;
60+
}

0 commit comments

Comments
ย (0)