Skip to content

Commit 12b4a1e

Browse files
committed
sadie100: number of islands solution
1 parent 2e15e1e commit 12b4a1e

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

number-of-islands/sadie100.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
m x n visited 이중배열을 만들고 grid를 탐색,
3+
visited false면서 1값이 있는 타일이 있으면 dfs로 상하좌우를 탐색, visited true로 만든 뒤 result+=1한다
4+
탐색이 마치면 result를 리턴한다
5+
6+
시간복잡도 : O(M + N)
7+
공간복잡도 : O(M + N) - visited
8+
*/
9+
10+
const dx = [0, 1, -1, 0]
11+
const dy = [1, 0, 0, -1]
12+
13+
function numIslands(grid: string[][]): number {
14+
const visited = Array.from({ length: grid.length }, () =>
15+
new Array(grid[0].length).fill(false),
16+
)
17+
let result = 0
18+
19+
function search(row: number, col: number) {
20+
visited[row][col] = true
21+
22+
for (let i = 0; i < 4; i++) {
23+
const newRow = row + dx[i]
24+
const newCol = col + dy[i]
25+
26+
if (newRow < 0 || newRow >= grid.length) continue
27+
if (newCol < 0 || newCol >= grid[0].length) continue
28+
29+
if (visited[newRow][newCol] === false && grid[newRow][newCol] === '1') {
30+
search(newRow, newCol)
31+
}
32+
}
33+
}
34+
35+
for (let i = 0; i < grid.length; i++) {
36+
for (let j = 0; j < grid[0].length; j++) {
37+
if (visited[i][j] === false && grid[i][j] === '1') {
38+
search(i, j)
39+
result += 1
40+
}
41+
}
42+
}
43+
44+
return result
45+
}

0 commit comments

Comments
 (0)