Skip to content

Commit dac1ef3

Browse files
author
이연수
committed
number of island
1 parent 0d24fb4 commit dac1ef3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package leetcode_study
2+
3+
4+
/*
5+
* 섬의 개수를 구하는 문제
6+
* bfs를 사용해 문제 해결
7+
* 시간 복잡도: O(n^2)
8+
* -> 이중 반복문을 통해 모든 배열을 순회
9+
* -> bfs queue 순회
10+
* 공간 복잡도: O(n^2)
11+
* -> 방문을 표시하는 board
12+
* -> bfs에 사용되는 queue size
13+
* */
14+
val dx = listOf(0, 1, -1, 0)
15+
val dy = listOf(1, 0, 0, -1)
16+
17+
fun numIslands(grid: Array<CharArray>): Int {
18+
val board = Array(grid.size) { BooleanArray(grid[0].size) { false } }
19+
var result = 0
20+
for (i in grid.indices) {
21+
for (j in grid[0].indices) {
22+
if (grid[i][j] == '1' && board[i][j] == false) {
23+
bfs(grid, board, i ,j)
24+
result += 1
25+
}
26+
}
27+
}
28+
return result
29+
}
30+
31+
fun bfs(grid: Array<CharArray>, board: Array<BooleanArray>, x: Int, y: Int) {
32+
val queue = ArrayDeque<Pair<Int, Int>>()
33+
queue.add(Pair(x, y))
34+
board[x][y] = true
35+
36+
while (queue.isNotEmpty()) {
37+
val (row, col) = queue.removeFirst()
38+
for (i in IntRange(0, 3)) {
39+
val nx = row + dx[i]
40+
val ny = col + dy[i]
41+
if (nx >= 0 && nx < grid.size && ny >= 0 && ny < grid[0].size && !board[nx][ny] && grid[nx][ny] == '1') {
42+
queue.add(Pair(nx, ny))
43+
board[nx][ny] = true
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)