-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path827.cpp
More file actions
52 lines (52 loc) · 1.85 KB
/
827.cpp
File metadata and controls
52 lines (52 loc) · 1.85 KB
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
class Solution {
public:
vector<pair<int, int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void dfs(vector<vector<int>>& grid, int x, int y, int index, unordered_map<int, int>& islandSize) {
int n = grid.size();
grid[x][y] = index;
islandSize[index]++;
for (auto& direction : directions) {
int xx = x + direction.first;
int yy = y + direction.second;
if (xx < 0 || xx >= n || yy < 0 || yy >= n) continue;
if (grid[xx][yy] != 1) continue;
dfs(grid, xx, yy, index, islandSize);
}
}
int largestIsland(vector<vector<int>>& grid) {
int n = grid.size();
int index = -1;
unordered_map<int, int> islandSize;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) dfs(grid, i, j, index, islandSize);
index--;
}
}
int res = 0;
for (auto& [k, v] : islandSize) {
res = max(res, v);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) {
unordered_map<int, int> temp;
int cnt = 1;
for (auto& direction : directions) {
int xx = i + direction.first;
int yy = j + direction.second;
if (xx < 0 || xx >= n || yy < 0 || yy >=n ) continue;
if (grid[xx][yy] == 0) continue;
int key = grid[xx][yy];
temp[key] = islandSize[key];
}
for (auto& [k, v] : temp) {
cnt += v;
}
res = max(res, cnt);
}
}
}
return res;
}
};