Skip to main content

1706. Where Will the Ball Fall

https://leetcode.com/problems/where-will-the-ball-fall/

Python

DFS

class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n = len(grid),len(grid[0])
def dfs(row,col):
if row == m:
return col

new_col = col+grid[row][col]

if new_col == n or new_col == -1 \
or grid[row][new_col]!=grid[row][col]:
return -1

return dfs(row+1,new_col)

result = []
for i in range(n):
result.append(dfs(0, i))
return result