827. Making A Large Island

In a 2D grid of 0s and 1s, 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 1s).

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);
            }
            
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值