803. Bricks Falling When Hit

We have a grid of 1s and 0s; the 1s in a cell represent bricks.  A brick will not drop if and only if it is directly connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.

We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), the brick (if it exists) on that location will disappear, and then some other bricks may drop because of that erasure.

Return an array representing the number of bricks that will drop after each erasure in sequence.

Example 1:
Input: 
grid = [[1,0,0,0],[1,1,1,0]]
hits = [[1,0]]
Output: [2]
Explanation: 
If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.
Example 2:
Input: 
grid = [[1,0,0,0],[1,1,0,0]]
hits = [[1,1],[1,0]]
Output: [0,0]
Explanation: 
When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. So each erasure will cause no bricks dropping.  Note that the erased brick (1, 0) will not be counted as a dropped brick.

 

Note:

  • The number of rows and columns in the grid will be in the range [1, 200].
  • The number of erasures will not exceed the area of the grid.
  • It is guaranteed that each erasure will be different from any other erasure, and located inside the grid.
  • An erasure may refer to a location with no brick - if it does, no bricks drop.

思路:对每个hit从top进行n次遍历(n等于top等于1的列数),TLE,因为每次都需要从top遍历多次,如果top等于1的很多开销就比较大

那就从删除的地方进行遍历,但是我怎么知道遍历到的点有没有早就掉下来呢?所以需要逆向思维

先全部删掉,然后一个个加进去

Here is a example, you can walk from the last step to the first step to see how we transfer the question:

image
image
image
image


class Solution:
    def hitBricks(self, grid, hits):
        """
        :type grid: List[List[int]]
        :type hits: List[List[int]]
        :rtype: List[int]
        """
        n, m = len(grid), len(grid[0])
        dirs = [[1,0],[-1,0],[0,1],[0,-1]]
        for i,j in hits:
            grid[i][j] = 0 if grid[i][j]==1 else -1
        
        # call bfs only if can connect to top
        def bfs(i,j):
            q, qq = [[i,j]], []
            cnt =  0
            grid[i][j] = 2
            while q:
                while q:
                    ti, tj = q.pop()
                    for di,dj in dirs:
                        tti, ttj=ti+di, tj+dj
                        if 0<=tti<n and 0<=ttj<m and grid[tti][ttj]==1:
                            qq.append([tti,ttj])
                            grid[tti][ttj] = 2   # when cnt++, mark grid at once
                            cnt += 1
                q,qq = qq,q
            return cnt
        
        def isConnectToTop(i,j):
            if i==0: return True
            for di,dj in dirs:
                tti, ttj=i+di, j+dj
                if 0<=tti<n and 0<=ttj<m and grid[tti][ttj]==2: return True
            return False
        
        # init
        for i in range(m):
            if grid[0][i]==1: bfs(0, i)
        
        res = []
        for i,j in hits[::-1]:
            if grid[i][j]==0 : 
                grid[i][j]=1
                if isConnectToTop(i, j):
                    res.append(bfs(i,j))
                else:
                    res.append(0)
            else:
                res.append(0)
        return res[::-1]
 

还可以写的更简洁

class Solution:
    def hitBricks(self, grid, hits):
        """
        :type grid: List[List[int]]
        :type hits: List[List[int]]
        :rtype: List[int]
        """

        m, n = len(grid), len(grid[0])
        
        # Connect unconnected bricks and 
        def dfs(i, j):
            if not (0<=i<m and 0<=j<n) or grid[i][j]!=1:
                return 0
            ret = 1
            grid[i][j] = 2
            ret += sum(dfs(x, y) for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)])
            return ret
        
        # Check whether (i, j) is connected to Not Falling Bricks
        def is_connected(i, j):
            return i==0 or any([0<=x<m and 0<=y<n and grid[x][y]==2 for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]])
        
        # Mark whether there is a brick at the each hit
        for i, j in hits:
            grid[i][j] -= 1
                
        # Get grid after all hits
        for i in range(n):
            dfs(0, i)
        
        # Reversely add the block of each hits and get count of newly add bricks
        ret = [0]*len(hits)
        for k in reversed(range(len(hits))):
            i, j = hits[k]
            grid[i][j] += 1
            if grid[i][j]==1 and is_connected(i, j):
                ret[k] = dfs(i, j)-1
            
        return ret

官方给的解答是union-find?有时间在写

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值