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.
题解:dfs深搜,自己的解法没有用通过维护一个数组来记录每点所在地区面积这样遍历0的点时候只要计算四周的点的面积直接+1就可以而不是自己的在dfs等于0的点
class Solution {
public:
int largestIsland(vector<vector<int>>& grid) {
vector<vector<int>> g=grid;
int ans=0;
for(int i=0;i<g.size();i++){
for(int j=0;j<g[i].size();j++){
int cnt=0;
dfs(g,i,j,cnt);
ans=max(ans,cnt);
}
}
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[i].size();j++){
if(grid[i][j]==0){
vector<vector<int>> gg=grid;
gg[i][j]=1;
int cnt=0;
dfs(gg,i,j,cnt);
ans=max(cnt,ans);
}
}
}
return ans;
}
void dfs(vector<vector<int>>& grid,int i,int j,int& cnt){
if(i<0||i>=grid.size()||j<0||j>=grid[i].size()||grid[i][j]==0) return;
grid[i][j]=0;
cnt++;
dfs(grid,i,j-1,cnt);
dfs(grid,i,j+1,cnt);
dfs(grid,i-1,j,cnt);
dfs(grid,i+1,j,cnt);
}
};
别人的解法:
class Solution {
public:
int largestIsland(vector<vector<int>>& grid) {
color_ = 1;
g_ = &grid;
m_ = grid.size();
n_ = grid[0].size();
unordered_map<int, int> areas; // color -> area
int ans = 0;
for (int i = 0; i < m_; ++i)
for (int j = 0; j < n_; ++j)
if (grid[i][j] == 1) {
++color_;
areas[color_] = getArea(j, i);
ans = max(ans, areas[color_]);
}
for (int i = 0; i < m_; ++i)
for (int j = 0; j < n_; ++j)
if (grid[i][j] == 0) {
int area = 1;
for (int color : set<int>{getColor(j, i - 1), getColor(j, i + 1),
getColor(j - 1, i), getColor(j + 1, i)})
area += areas[color];
ans = max(ans, area);
}
return ans;
}
private:
int m_;
int n_;
int color_;
vector<vector<int>>* g_; // does not own the object.
int getColor(int x, int y) {
return (x < 0 || x >= n_ || y < 0 || y >= m_) ? 0 : (*g_)[y][x];
}
// Return the area of a connected component, set all elements to color_.
int getArea(int x, int y) {
if (x < 0 || x >= n_ || y < 0 || y >= m_ || (*g_)[y][x] != 1) return 0;
(*g_)[y][x] = color_;
return 1 + getArea(x - 1, y) + getArea(x + 1, y)
+ getArea(x, y - 1) + getArea(x, y + 1);
}
};