LeetCode827. Making A Large Island

一、题目

You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

Return the size of the largest island in grid after applying this operation.

An island is a 4-directionally connected group of 1s.

Example 1:

Input: grid = [[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: grid = [[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: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can’t change any 0 to 1, only one island with area = 4.

Constraints:

n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.

二、题解

class Solution {
public:
    int count = 0;
    int dirs[4][2] = {1,0,0,1,-1,0,0,-1};
    void dfs(vector<vector<int>>& grid,int x,int y,int mark){
        grid[x][y] = mark;
        for(int i = 0;i < 4;i++){
            int nextX = x + dirs[i][0];
            int nextY = y + dirs[i][1];
            if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;
            if(grid[nextX][nextY] == 1){
                dfs(grid,nextX,nextY,mark);
                count++;
            }
        }
    }
    int largestIsland(vector<vector<int>>& grid) {
        int m = grid.size(),n = grid[0].size();
        unordered_map<int,int> map;
        int mark = 2;
        bool allLand = true;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                count = 1;
                if(grid[i][j] == 0) allLand = false;
                if(grid[i][j] == 1){
                    dfs(grid,i,j,mark);
                    map[mark] = count;
                    mark++;
                }
            }
        }
        if(allLand) return m * n;
        int res = 0;
        unordered_set<int> visitedGrid;
        //遍历所有值为0的节点
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                int sum = 1;
                visitedGrid.clear();
                if(grid[i][j] == 0){
                    for(int index = 0;index < 4;index++){
                        int nextX = i + dirs[index][0];
                        int nextY = j + dirs[index][1];
                        if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;
                        if (visitedGrid.count(grid[nextX][nextY])) continue;
                        sum += map[grid[nextX][nextY]];
                        visitedGrid.insert(grid[nextX][nextY]);
                    }
                }
                res = max(res,sum);
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值