Skip to content

Commit ef3394e

Browse files
committed
feat: Upload number-of-islands(typescript)
1 parent 1f12369 commit ef3394e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

number-of-islands/mike2ox.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* https://leetcode.com/problems/number-of-islands/
3+
* 풀이방법: BFS를 사용하여 섬의 개수를 구함
4+
*
5+
* 시간복잡도: O(n * m) (n: 그리드의 행, m: 그리드의 열)
6+
* 공간복잡도: O(n * m) (그리드의 모든 요소를 방문)
7+
*/
8+
9+
function numIslands(grid: string[][]): number {
10+
if (!grid.length) return 0; // 그리드가 비어있는 경우
11+
12+
const rows = grid.length;
13+
const cols = grid[0].length;
14+
let islands = 0;
15+
16+
const bfs = (startRow: number, startCol: number) => {
17+
const q: number[][] = [[startRow, startCol]];
18+
grid[startRow][startCol] = "0";
19+
20+
const directions = [
21+
[1, 0],
22+
[-1, 0],
23+
[0, 1],
24+
[0, -1],
25+
]; // 상하좌우
26+
27+
while (q.length) {
28+
const [r, c] = q.shift()!;
29+
30+
for (const [dx, dy] of directions) {
31+
const newR = r + dx;
32+
const newC = c + dy;
33+
34+
if (
35+
newR >= 0 &&
36+
newR < rows &&
37+
newC >= 0 &&
38+
newC < cols &&
39+
grid[newR][newC] === "1"
40+
) {
41+
q.push([newR, newC]);
42+
grid[newR][newC] = "0";
43+
}
44+
}
45+
}
46+
};
47+
48+
for (let r = 0; r < rows; r++) {
49+
for (let c = 0; c < cols; c++) {
50+
if (grid[r][c] === "1") {
51+
islands++;
52+
bfs(r, c);
53+
}
54+
}
55+
}
56+
57+
return islands;
58+
}

0 commit comments

Comments
 (0)