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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| class Solution { public: int cnt = 0; void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visted, int x, int y, int mark) { if (visted[x][y]) return; cnt++; visted[x][y] = true; grid[x][y] = mark; 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 (pair<int, int> neigbor : neigbors) { if (neigbor.first >= grid.size() || neigbor.second >= grid[0].size() || neigbor.first < 0 || neigbor.second < 0) continue; if (grid[neigbor.first][neigbor.second] == 0) continue; if (visted[neigbor.first][neigbor.second]) continue; dfs(grid, visted, neigbor.first, neigbor.second, mark); } }
int largestIsland(vector<vector<int>>& grid) { unordered_map<int, int> islandsGridNum; int mark = 2; bool allIsland = true; vector<vector<bool>> visted(grid.size(),vector<bool>(grid[0].size(), false)); for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if(grid[i][j] == 0) allIsland = false; if (!visted[i][j] && grid[i][j] == 1) { cnt = 0; dfs(grid, visted, i, j, mark); islandsGridNum[mark] = cnt; mark++; } } }
if (allIsland) return grid.size() * grid[0].size();
int res = 0; unordered_set<int> vistedIsland; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { int sum = 1; vistedIsland.clear(); if (grid[i][j] == 0) { pair<int, int> neigbors[4]{ pair<int, int>(i, j + 1), pair<int, int>(i + 1, j), pair<int, int>(i, j - 1), pair<int, int>(i - 1, j)}; for (pair<int, int> neigbor : neigbors) { if (neigbor.first >= grid.size() || neigbor.second >= grid[0].size() || neigbor.first < 0 || neigbor.second < 0) continue; if (grid[neigbor.first][neigbor.second] == 0) continue; if (vistedIsland.find( grid[neigbor.first][neigbor.second]) != vistedIsland.end()) continue; vistedIsland.insert( grid[neigbor.first][neigbor.second]); sum += islandsGridNum[grid[neigbor.first][neigbor.second]]; } } res = max(sum, res); } } return res; } };
|