Skip to content

Commit c7edc19

Browse files
committed
803
1 parent f083626 commit c7edc19

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

DFS/traditionalDFS/803.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## Bricks Falling When Hit
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/bricks-falling-when-hit/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
> 最坏情况:O(n^2)
18+
19+
```python
20+
class Solution:
21+
def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
22+
m, n = len(grid), len(grid[0])
23+
24+
# Connect unconnected bricks and Sum them all
25+
def dfs(i, j):
26+
if not (0<=i<m and 0<=j<n) or grid[i][j]!=1:
27+
return 0
28+
ret = 1
29+
grid[i][j] = 2
30+
ret += sum(dfs(x, y) for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)])
31+
return ret
32+
33+
# Check whether (i, j) is connected to Not Falling Bricks
34+
def is_connected(i, j):
35+
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)]])
36+
37+
# Mark whether there is a brick at the each hit
38+
for i, j in hits:
39+
grid[i][j] -= 1
40+
41+
# Get grid after all hits
42+
for i in range(n):
43+
dfs(0, i)
44+
45+
# Reversely add the block of each hits and get count of newly add bricks
46+
ret = [0]*len(hits)
47+
for k in reversed(range(len(hits))):
48+
i, j = hits[k]
49+
grid[i][j] += 1
50+
if grid[i][j]==1 and is_connected(i, j):
51+
ret[k] = dfs(i, j)-1
52+
53+
return ret
54+
```

0 commit comments

Comments
 (0)