| 1 | fun countIslands(matrix: MutableList<MutableList<Int>>): Int { |
| 2 | if (matrix.isEmpty()) { |
| 3 | return 0 |
| 4 | } |
| 5 | var count = 0 |
| 6 | for (r in matrix.indices) { |
| 7 | for (c in matrix[0].indices) { |
| 8 | // If a land cell is found, perform DFS to explore the full |
| 9 | // island, and include this island in our count. |
| 10 | if (matrix[r][c] == 1) { |
| 11 | dfs(r, c, matrix) |
| 12 | count++ |
| 13 | } |
| 14 | } |
| 15 | } |
| 16 | return count |
| 17 | } |
| 18 | |
| 19 | fun dfs(r: Int, c: Int, matrix: MutableList<MutableList<Int>>) { |
| 20 | // Mark the current land cell as visited. |