|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int largestIsland(vector<vector<int>>& grid) { |
| 4 | + if (grid.empty()) |
| 5 | + return 0; |
| 6 | + |
| 7 | + int n = grid.size(); |
| 8 | + vector<vector<int>> labels(n,vector<int>(n, 0)); |
| 9 | + unordered_map<int, int> islandSizes; |
| 10 | + int label = 1; |
| 11 | + int maxSize = 0; |
| 12 | + |
| 13 | + int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 14 | + |
| 15 | + for (int i = 0; i < n; ++i) { |
| 16 | + for (int j = 0; j < n; ++j) { |
| 17 | + if (grid[i][j] == 1 && labels[i][j] == 0) { |
| 18 | + int size = 0; |
| 19 | + vector<pair<int, int>> stack; |
| 20 | + stack.push_back({i, j}); |
| 21 | + labels[i][j] = label; |
| 22 | + |
| 23 | + while (!stack.empty()) { |
| 24 | + auto [x, y] = stack.back(); |
| 25 | + stack.pop_back(); |
| 26 | + size++; |
| 27 | + |
| 28 | + for (auto [dx, dy] : dirs) { |
| 29 | + int nx = x + dx, ny = y + dy; |
| 30 | + if (nx >= 0 && nx < n && ny >= 0 && ny < n && |
| 31 | + grid[nx][ny] == 1 && labels[nx][ny] == 0) { |
| 32 | + labels[nx][ny] = label; |
| 33 | + stack.push_back({nx, ny}); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + islandSizes[label] = size; |
| 39 | + maxSize = max(maxSize, size); |
| 40 | + label++; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + for (int i = 0; i < n; ++i) { |
| 46 | + for (int j = 0; j < n; ++j) { |
| 47 | + if (grid[i][j] == 0) { |
| 48 | + unordered_set<int> neighborLabels; |
| 49 | + int total = 1; |
| 50 | + |
| 51 | + for (auto [dx, dy] : dirs) { |
| 52 | + int nx = i + dx, ny = j + dy; |
| 53 | + if (nx >= 0 && nx < n && ny >= 0 && ny < n && |
| 54 | + grid[nx][ny] == 1) { |
| 55 | + neighborLabels.insert(labels[nx][ny]); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + for (int lbl : neighborLabels) { |
| 60 | + total += islandSizes[lbl]; |
| 61 | + } |
| 62 | + |
| 63 | + maxSize = max(maxSize, total); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return maxSize; |
| 69 | + } |
| 70 | +}; |
0 commit comments