[Python3] O(m*n) simulation approach
The idea is to simulate what\'s happening for each ball when dropped at different (0,col). If a ball get out of the box i.e., row==len(grid), we just return the
The idea is to simulate what\'s happening for each ball when dropped at different (0,col). If a ball get out of the box i.e., row==len(grid), we just return the column. if the new column is already out of the box or the next cell doesn\'t equal to grid[row][col] the ball will get stuck and we just return -1.\n```\nclass Solution:\n    def findBall(self, grid: List[List[int]]) -> List[int]:\n        m,n = len(grid),len(grid[0])\n        def check(row,col):\n            ### If a ball get out of the box, return col\n            if row==m:\n                return col\n                \n            ### note that since grid contains 1 and -1 representing to right and to left, \n            ### we can just add the grid[row][col] to current collumn to get the new column\n            new_col = col+grid[row][col]\n            \n            ### if the new column is already out of the box \n            ### or the neighbor cell doesn\'t equal to grid[row][col] \n            ### the ball will get stuck and we just return -1\n            if new_col==n or new_col==-1 or grid[row][new_col]!=grid[row][col]:\n                return -1\n            else:\n                return check(row+1,new_col)\n        res = []\n        for i in range(n):\n            res.append(check(0,i))\n        return res\n```\n\n**Iterative instead of recursion**\n```python\nclass Solution:\n    def findBall(self, grid: List[List[int]]) -> List[int]:\n        m,n = len(grid),len(grid[0])\n        res = [-1 for i in range(n)]\n        \n        for col in range(n):\n            curCol = col\n            for row in range(m):\n                newCol = curCol + grid[row][curCol]\n                if newCol==-1 or newCol==n or grid[row][newCol]!=grid[row][curCol]:\n                    break\n                curCol = newCol\n            else:\n                res[col] = curCol\n        \n        return res\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
[]