Where Will the Ball Fall
Understand how to simulate ball movement in a 2D grid where cells redirect balls left or right. Explore conditions causing balls to get stuck or fall out and implement a solution that returns the exit column or -1 if stuck. Practice traversing matrices and handling edge cases.
We'll cover the following...
Statement
You have balls and a 2D grid of size representing a box. The box is open on the top and bottom sides. Each cell in the box has a diagonal that can redirect a ball to the right or the left. You must drop balls at each column’s top. The goal is to determine whether each ball will fall out of the bottom or become stuck in the box. Each cell in the grid has a value of or .
- represents that the grid will redirect the ball to the right.
- represents that the grid will redirect the ball to the left.
A ball gets stuck if it hits a V-shaped pattern between two grids or if a grid redirects the ball into either wall of the box.
The solution should return an array of size , with the element indicating the column that the ball falls out of, or it becomes if it’s stuck. If the ball drops from column and falls out from column , then in the result array, index contains value .
Constraints:
-
grid.length -
grid[i].length grid[i][j]is or .
Example
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Where Will the Ball Fall
What will be the output of the grid given below?
grid = [[1, 1], [-1, -1]]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;class FindExitColumn{public static int[] findExitColumn(int[][] grid) {// Replace this placeholder return statement with your codereturn new int[]{};}}