-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path803.bricks-falling-when-hit.py
43 lines (35 loc) · 1.33 KB
/
803.bricks-falling-when-hit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#
# @lc app=leetcode id=803 lang=python3
#
# [803] Bricks Falling When Hit
#
# @lc code=start
class Solution:
def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
# Connect unconnected bricks and Sum them all
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
# @lc code=end