1706. Where Will the Ball Fall
class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
def dfs(y, x):
if y == M:
return x
if x < 0 or x >= N or grid[y][x] == 0:
return -1
if grid[y][x] == 1:
return dfs(y+1, x+1)
elif grid[y][x] == -1:
return dfs(y+1, x-1)
M, N = len(grid), len(grid[0])
answer = []
for i in range(M):
if grid[i][0] == -1:
grid[i][0] = 0
if grid[i][N-1] == 1:
grid[i][N-1] = 0
for j in range(1, N):
if grid[i][j-1] == 1 and grid[i][j] == -1:
grid[i][j-1] = 0
grid[i][j] = 0
for i in range(N):
x = dfs(0, i)
if x == -1:
answer.append(-1)
else:
answer.append(x)
return answer
class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
def dfs(y, x):
if y == M:
return x
if (x == 0 and grid[y][0] == -1) or (x == N-1 and grid[y][N-1] == 1):
return -1
if (grid[y][x] == 1 and grid[y][x+1] == -1) or (grid[y][x] == -1 and grid[y][x-1] == 1):
return -1
return dfs(y+1, x + grid[y][x])
M, N = len(grid), len(grid[0])
return list(dfs(0, i) for i in range(N))