LeetCode Problem Workspace

Where Will the Ball Fall

Determine where each ball exits a diagonal board grid or if it gets stuck, using matrix simulation with careful traversal.

category

3

Topics

code_blocks

7

Code langs

hub

3

Related

Practice Focus

Medium · Array plus Matrix

bolt

Answer-first summary

Determine where each ball exits a diagonal board grid or if it gets stuck, using matrix simulation with careful traversal.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array plus Matrix

Try AiBox Copilotarrow_forward

Simulate dropping each ball column by column through the grid. Track movement according to the cell diagonals: 1 moves right, -1 moves left. Handle stuck cases where a ball encounters a wall or a 'V' pattern between boards. The result is an array mapping each ball to its exit column or -1 if it gets stuck, using DFS or iterative simulation to maintain correctness and clarity.

Problem Statement

You are given a 2-D m x n grid representing a box open on the top and bottom sides. Each cell contains a diagonal board directing a ball either to the right (1) or left (-1). Drop one ball at the top of each column. A ball may exit at the bottom or become stuck if it hits the box walls or a 'V' shaped blockage formed by adjacent boards.

Return an array where each element represents the exit column of the ball dropped at the corresponding top column, or -1 if the ball gets stuck. A ball is stuck when redirected into a wall or trapped between two adjacent boards forming a 'V' shape.

Examples

Example 1

Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]

Output: [1,-1,-1,-1,-1]

This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.

Example 2

Input: grid = [[-1]]

Output: [-1]

The ball gets stuck against the left wall.

Example 3

Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]

Output: [0,1,2,3,4,-1]

Example details omitted.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • grid[i][j] is 1 or -1.

Solution Approach

Simulate Ball Movement Iteratively

Iterate through each ball starting at the top of its column. At each row, check the direction from the grid cell. Move the ball right if 1, left if -1. Detect stuck conditions when the next column is out of bounds or forms a 'V' shape with adjacent cells. Record the exit column or -1.

Use Depth-First Search (DFS)

Implement DFS to traverse the path of each ball recursively. For each cell, determine the next cell based on the diagonal. Terminate recursion if the ball reaches the bottom or hits a stuck condition. DFS simplifies handling multiple rows and provides clear path tracing for debugging stuck scenarios.

Optimize with Early Exit Checks

Before moving the ball, check if the next move will go out of bounds or enter a 'V' trap. If so, immediately mark -1. This reduces unnecessary iterations and ensures early detection of stuck balls, which is crucial for large grids up to 100x100.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(m * n) since each ball may traverse all rows in its column. Space complexity is O(n) for storing the output array, or O(m) additional if using recursion in DFS for path tracking.

What Interviewers Usually Probe

  • Notice each ball moves independently through the grid; look for per-column simulation patterns.
  • Pay attention to the 'V' shaped stuck condition formed by adjacent cells and edge cases on walls.
  • Consider iterative versus recursive approaches to clearly handle ball paths and stuck detection.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to check the 'V' shaped block between two adjacent boards leading to incorrect stuck results.
  • Ignoring wall boundaries causing array index errors or wrong exit positions.
  • Mixing row and column indices, which can misdirect the ball in the simulation.

Follow-up variants

  • Return only the count of balls that successfully exit rather than their positions.
  • Allow arbitrary board angles represented by integers beyond 1 and -1, requiring generalized movement rules.
  • Simulate gravity in reverse from bottom to top to compute reachable top columns.

FAQ

What is the best way to handle balls getting stuck in 'Where Will the Ball Fall'?

Check for 'V' shaped patterns between adjacent cells and walls at every move. Mark -1 immediately when stuck conditions occur.

Can I use recursion to solve this grid simulation problem?

Yes, DFS works well for tracing each ball's path and handling stuck conditions naturally.

How do I detect a ball hitting the box wall?

Before moving left or right, verify the next column is within 0 to n-1. Exceeding this range means the ball is stuck.

Is there a way to optimize simulation for large grids?

Early exit checks for stuck conditions reduce unnecessary traversal, improving performance for grids up to 100x100.

Does the ball always exit at the bottom in this problem pattern?

No, balls can get stuck due to walls or 'V' shaped patterns; you must track each ball individually to determine its exit or stuck status.

terminal

Solution

Solution 1: Case Analysis + DFS

We can use DFS to simulate the movement of the ball. Design a function $\textit{dfs}(i, j)$, which represents the column where the ball will fall when it starts from row $i$ and column $j$. The ball will get stuck in the following cases:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        def dfs(i: int, j: int) -> int:
            if i == m:
                return j
            if j == 0 and grid[i][j] == -1:
                return -1
            if j == n - 1 and grid[i][j] == 1:
                return -1
            if grid[i][j] == 1 and grid[i][j + 1] == -1:
                return -1
            if grid[i][j] == -1 and grid[i][j - 1] == 1:
                return -1
            return dfs(i + 1, j + 1) if grid[i][j] == 1 else dfs(i + 1, j - 1)

        m, n = len(grid), len(grid[0])
        return [dfs(0, j) for j in range(n)]
Where Will the Ball Fall Solution: Array plus Matrix | LeetCode #1706 Medium