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 39 40 41 42 43 44 45
| class Solution { public: int rowNum; int columnNum; int cnt; void dfs(vector<vector<int>>& grid, int x, int y) { grid[x][y] = 0; cnt++; pair<int, int> neigbors[4]{ pair<int, int>(x, y + 1), pair<int, int>(x + 1, y), pair<int, int>(x, y - 1), pair<int, int>(x - 1, y)}; for (auto item : neigbors) { if (item.first < 0 || item.first >= rowNum || item.second < 0 || item.second >= columnNum) continue; if (grid[item.first][item.second] == 0) continue; dfs(grid, item.first, item.second); } } int numEnclaves(vector<vector<int>>& grid) { rowNum = grid.size(); columnNum = grid[0].size(); for (int i = 0; i < columnNum; i++) { if (grid[0][i] == 1) dfs(grid, 0, i); if (grid[rowNum - 1][i] == 1) dfs(grid, rowNum - 1, i); } for (int i = 0; i < rowNum; i++) { if (grid[i][0] == 1) dfs(grid, i, 0); if (grid[i][columnNum - 1] == 1) dfs(grid, i, columnNum - 1); } cnt = 0; for (int i = 0; i < rowNum; i++) { for (int j = 0; j < columnNum; j++) { if (grid[i][j] == 1) dfs(grid,i,j); } } return cnt; } };
|