| 19 | } |
| 20 | |
| 21 | void dfs(int r, int c, std::vector<std::vector<int>>& matrix) { |
| 22 | // Mark the current land cell as visited. |
| 23 | matrix[r][c] = -1; |
| 24 | // Define direction vectors for up, down, left, and right. |
| 25 | int dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; |
| 26 | // Recursively call DFS on each neighboring land cell to continue |
| 27 | // exploring this island. |
| 28 | for (int i = 0; i < 4; i++) { |
| 29 | int nextR = r + dirs[i][0]; |
| 30 | int nextC = c + dirs[i][1]; |
| 31 | if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) { |
| 32 | dfs(nextR, nextC, matrix); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | bool isWithinBounds(int r, int c, std::vector<std::vector<int>>& matrix) { |
| 38 | return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size(); |
no test coverage detected