|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `number-of-islands` { |
| 7 | + |
| 8 | + private data class Position( |
| 9 | + val x: Int, |
| 10 | + val y: Int |
| 11 | + ) { |
| 12 | + |
| 13 | + operator fun plus(other: Position) = Position(this.x + other.x, this.y + other.y) |
| 14 | + |
| 15 | + fun isNotOutOfIndexed(board: Array<CharArray>) = |
| 16 | + this.x < board.size && this.x >= 0 && this.y < board[0].size && this.y >= 0 |
| 17 | + |
| 18 | + companion object { |
| 19 | + val MOVES: List<Position> = listOf( |
| 20 | + Position(-1, 0), |
| 21 | + Position(0, 1), |
| 22 | + Position(1, 0), |
| 23 | + Position(0, -1), |
| 24 | + ) |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * BFS를 사용한 탐색 |
| 30 | + * TC: O(n * m), SC: O(n * m) |
| 31 | + */ |
| 32 | + fun numIslands(grid: Array<CharArray>): Int { |
| 33 | + val (row, col) = grid.size to grid.first().size |
| 34 | + val visited = Array(row) { BooleanArray(col) } |
| 35 | + var result = 0 |
| 36 | + |
| 37 | + for (x in 0 until row) { |
| 38 | + for (y in 0 until col) { |
| 39 | + if (!visited[x][y] && grid[x][y] == '1') { |
| 40 | + visited[x][y] = true |
| 41 | + bfs(x, y, grid, visited) |
| 42 | + result++ |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + return result |
| 47 | + } |
| 48 | + |
| 49 | + private fun bfs(x: Int, y: Int, grid: Array<CharArray>, visited: Array<BooleanArray>) { |
| 50 | + val queue = ArrayDeque<Position>().apply { |
| 51 | + this.add(Position(x, y)) |
| 52 | + } |
| 53 | + |
| 54 | + while (queue.isNotEmpty()) { |
| 55 | + val now = queue.removeFirst() |
| 56 | + for (move in Position.MOVES) { |
| 57 | + val moved = now + move |
| 58 | + if (moved.isNotOutOfIndexed(grid) && grid[moved.x][moved.y] == '1' && !visited[moved.x][moved.y]) { |
| 59 | + visited[moved.x][moved.y] = true |
| 60 | + queue.add(moved) |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + @Test |
| 68 | + fun `문자 이차원배열을 입력받으면 1로 이루어진 영역의 수를 반환한다`() { |
| 69 | + numIslands(arrayOf( |
| 70 | + charArrayOf('1','1','1','1','0'), |
| 71 | + charArrayOf('1','1','0','1','0'), |
| 72 | + charArrayOf('1','1','0','0','0'), |
| 73 | + charArrayOf('0','0','0','0','0') |
| 74 | + )) shouldBe 1 |
| 75 | + |
| 76 | + numIslands(arrayOf( |
| 77 | + charArrayOf('1','1','0','0','0'), |
| 78 | + charArrayOf('1','1','0','0','0'), |
| 79 | + charArrayOf('0','0','1','0','0'), |
| 80 | + charArrayOf('0','0','0','1','1') |
| 81 | + )) shouldBe 3 |
| 82 | + } |
| 83 | +} |
0 commit comments