-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1706_whereWillBallFall.py
41 lines (31 loc) · 1.27 KB
/
1706_whereWillBallFall.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
class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
'''
grid[i][j] == 1:
grid[i][j+1] == 1 -> True
grid[i][j+1] == -1 -> False
grid[i][j] == -1:
grid[i][j-1] == 1 -> False
grid[i][j-1] == -1 -> True
'''
rows = len(grid)
cols = len(grid[0])
possible_path = {}
def go_down(row, col):
if (row, col) in possible_path:
return possible_path[(row, col)]
if row == rows:
possible_path[(row, col)] = col
return possible_path[(row, col)]
if (col == 0 and grid[row][col] == -1) or (col == cols-1 and grid[row][col] == 1):
possible_path[(row, col)] = -1
return possible_path[(row, col)]
if grid[row][col] == 1:
possible_path[(row, col)] = go_down(row+1, col+1) if grid[row][col+1] == 1 else -1
else:
possible_path[(row, col)] = go_down(row+1, col-1) if grid[row][col-1] == -1 else -1
return possible_path[(row, col)]
output = [-1 for _ in range(cols)]
for col in range(cols):
output[col] = go_down(0, col)
return output