Skip to content

Commit 5c64755

Browse files
committed
#258 Number of Islands
1 parent 20c9929 commit 5c64755

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

number-of-islands/sukyoungshin.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function numIslands(grid: string[][]): number {
2+
let count = 0;
3+
4+
for (let row = 0; row < grid.length; row++) {
5+
for (let col = 0; col < grid[0].length; col++) {
6+
if (grid[row][col] === "1") {
7+
count++; // 새로운 섬 발견!
8+
dfs(row, col); // 연결된 모든 "1"을 0으로 바꾸기
9+
}
10+
}
11+
}
12+
13+
function dfs(row: number, col: number) {
14+
// 1. 범위를 벗어나거나 이미 물(0)이면 return
15+
if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length)
16+
return;
17+
if (grid[row][col] === "0") return;
18+
19+
// 2. 현재 좌표를 0으로 바꾸고
20+
grid[row][col] = "0";
21+
22+
// 3. 상하좌우로 dfs 재귀 호출
23+
dfs(row - 1, col); // 위
24+
dfs(row + 1, col); // 아래
25+
dfs(row, col - 1); // 왼쪽
26+
dfs(row, col + 1); // 오른쪽
27+
}
28+
29+
return count;
30+
}

0 commit comments

Comments
 (0)