| 17 | } |
| 18 | |
| 19 | fun dfs(r: Int, c: Int, matrix: MutableList<MutableList<Int>>) { |
| 20 | // Mark the current land cell as visited. |
| 21 | matrix[r][c] = -1 |
| 22 | // Define direction vectors for up, down, left, and right. |
| 23 | val dirs = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) |
| 24 | // Recursively call DFS on each neighboring land cell to continue |
| 25 | // exploring this island. |
| 26 | for (d in dirs) { |
| 27 | val nextR = r + d.first |
| 28 | val nextC = c + d.second |
| 29 | if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) { |
| 30 | dfs(nextR, nextC, matrix) |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | fun isWithinBounds(r: Int, c: Int, matrix: MutableList<MutableList<Int>>): Boolean { |
| 36 | return r in matrix.indices && c in matrix[0].indices |
no test coverage detected