1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public: void dfs(vector<vector<int>>& grid, int i, int j, int m, int n) { if (i < 0 || i > m - 1 || j < 0 || j > n - 1) { return; } if (grid[i][j] == 1) { return; } grid[i][j] = 1; dfs(grid, i - 1, j, m, n); dfs(grid, i + 1, j, m, n); dfs(grid, i, j - 1, m, n); dfs(grid, i, j + 1, m, n); } int closedIsland(vector<vector<int>>& grid) { int result = 0; int m = grid.size(); int n = grid[0].size(); for (int i = 0; i < m; i++) { dfs(grid, i, 0, m, n); dfs(grid, i, n - 1, m, n); } for (int i = 0; i < n; i++) { dfs(grid, 0, i, m, n); dfs(grid, m - 1, i, m, n); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { result++; dfs(grid, i, j, m, n); } } } return result; } };
|