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:

803. Bricks Falling When Hit_第1张图片
803. Bricks Falling When Hit_第2张图片
803. Bricks Falling When Hit_第3张图片
803. Bricks Falling When Hit_第4张图片


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

还可以写的更简洁

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

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

你可能感兴趣的:(leetcode,dfs,bfs)