In a 2D grid of 0
s and 1
s, we change at most one 0
to a 1
.
After, what is the size of the largest island? (An island is a 4-directionally connected group of 1
s).
Example 1:
Input: [[1, 0], [0, 1]] Output: 3 Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: [[1, 1], [1, 0]] Output: 4 Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: [[1, 1], [1, 1]] Output: 4 Explanation: Can't change any 0 to 1, only one island with area = 4.
C++ 代码:
class Solution {
private:
vector<vector<int>> dirs={{1,0},{-1,0},{0,1},{0,-1}};
public:
int largestIsland(vector<vector<int>>& grid) {
unordered_map<int, int> areas; // color -> area
int m = grid.size(),n = grid[0].size();
int color =2;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == 1){
//cout<<i<<" "<<j<<endl;
dfs(grid,i,j,areas,color);
++color;
}
}
}
int ret = 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == 0){
int area_t = 1;
set<int> colors;
for(auto dir:dirs){
int x = i+dir[0], y= j+dir[1];
if(x<0 || x>=grid.size() || y<0 || y>=grid[0].size() || grid[x][y] == 0) continue;
int c = grid[x][y];
if(!colors.count(c)){
area_t += areas[c];
colors.insert(c);
}
}
ret = max(ret,area_t);
}
}
}
return ret==0 ? m*n:ret;
}
void dfs(vector<vector<int>>& grid, int i, int j, unordered_map<int,int>& areas, int color){
grid[i][j] = color;
if(!areas.count(color)) areas[color] = 0;
areas[color]+=1;
for(auto dir:dirs){
int x = i+dir[0], y= j+dir[1];
if(x<0 || x>=grid.size() || y<0 || y>=grid[0].size() || grid[x][y] == 0) continue;
if(grid[x][y] == 1){
dfs(grid,x,y,areas,color);
}
}
}
};