305. Number of Islands II

https://leetcode.com/problems/number-of-islands-ii/description/?envType=company&envId=tiktok&favoriteSlug=tiktok-three-months

You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's).

We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1,1,2,3]
Explanation:
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.

Example 2:

Input: m = 1, n = 1, positions = [[0,0]]
Output: [1]
class Solution:
    def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
        res=[0 for i in range(len(positions))]
        parent={}

        def find(node):
            if parent[node]!=node:
                parent[node]=find(parent[node])
            return parent[node]

        def union(n1,n2):
            p1,p2=find(n1),find(n2)
            if p1==p2:
                return False
            else:
                parent[p1]=p2
                return True
        
        res=[]
        count=0
        for (i,j) in positions:
            if (i,j) not in parent:
                parent[(i,j)]=(i,j)
                count+=1
            for x,y in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
                if (x,y) in parent:
                    if union((x,y),(i,j)):
                        count-=1
            res.append(count)
        return res

parent[p1]=p2

这个方向没有问题但是一定连parent

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值