| 1 | #include <vector> |
| 2 | |
| 3 | int countIslands(std::vector<std::vector<int>>& matrix) { |
| 4 | if (matrix.empty()) { |
| 5 | return 0; |
| 6 | } |
| 7 | int count = 0; |
| 8 | for (int r = 0; r < matrix.size(); r++) { |
| 9 | for (int c = 0; c < matrix[0].size(); c++) { |
| 10 | // If a land cell is found, perform DFS to explore the full |
| 11 | // island, and include this island in our count. |
| 12 | if (matrix[r][c] == 1) { |
| 13 | dfs(r, c, matrix); |
| 14 | count += 1; |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | return count; |
| 19 | } |
| 20 | |
| 21 | void dfs(int r, int c, std::vector<std::vector<int>>& matrix) { |
| 22 | // Mark the current land cell as visited. |