class Solution
{
public:
unordered_map<int, int> component;
void dfs(vector<vector<int>> &grid, int x, int y, int color)
{
int n = grid.size();
int m = grid[0].size();
component[color]++;
grid[x][y] = color;
if (x - 1 >= 0 && grid[x - 1][y] == 1)
{
dfs(grid, x - 1, y, color);
}
if (x + 1 < n && grid[x + 1][y] == 1)
{
dfs(grid, x + 1, y, color);
}
if (y - 1 >= 0 && grid[x][y - 1] == 1)
{
dfs(grid, x, y - 1, color);
}
if (y + 1 < m && grid[x][y + 1] == 1)
{
dfs(grid, x, y + 1, color);
}
return;
}
int largestIsland(vector<vector<int>> &grid)
{
int n = grid.size();
int m = grid[0].size();
int color = 2;
int ans = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
dfs(grid, i, j, color);
ans = max(ans, component[color]);
color++;
}
}
}
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
unordered_set<int> ct;
if (grid[i][j] == 0)
{
int a = 0, b = 0, c = 0, d = 0;
if (i - 1 >= 0 && grid[i - 1][j] != 0)
{
int col = grid[i - 1][j];
if (ct.find(col) == ct.end())
{
a += component[col];
ct.insert(col);
}
}
if (i + 1 < n && grid[i + 1][j] != 0)
{
int col = grid[i + 1][j];
if (ct.find(col) == ct.end())
{
b += component[col];
ct.insert(col);
}
}
if (j - 1 >= 0 && grid[i][j - 1] != 0)
{
int col = grid[i][j - 1];
if (ct.find(col) == ct.end())
{
c += component[col];
ct.insert(col);
}
}
if (j + 1 < m && grid[i][j + 1] != 0)
{
int col = grid[i][j + 1];
if (ct.find(col) == ct.end())
{
d += component[col];
ct.insert(col);
}
}
ans = max(ans, a + b + c + d + 1);
}
}
}
return ans;
}
};