LeetCode 1706: Where Will the Ball Fall

link

The rules are local involving just two cells: current cell and the cell to its left or to its right. Moves can happen in three directions: down, left, and right. For an entry column, we start with row = -1, so first down move is valid. In the beginning of each iteration we maintain the invariant: going down is valid. Within an iteration we consider the other two directions: left or right. If we hit borders or we hit “V”, we are stuck and try next entry column.

Time: \mathcal{O}(m \cdot n), space: \mathcal{O}(\texttt{output-size}).

class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        m, n = len(grid), len(grid[0])
        exits = [-1] * n

        for entry in range(n):
            r, c = -1, entry
            while r < m:
                # Invariant: Going down is valid
                r += 1
                if r == m:
                    exits[ entry ] = c
                    break

                # next cell exist?
                curr_dir = grid[r][c]
                next_c = (c+1) if curr_dir == 1 else (c-1)
                if (next_c < 0) or (next_c >= n):
                    break
                # stuck?
                next_dir = grid[r][next_c]
                if next_dir != curr_dir:
                    break
                
                # Go to next cell
                c = next_c

        return exits

Leave a comment