|
| 1 | +/** |
| 2 | + * 1706. Where Will the Ball Fall |
| 3 | + * https://leetcode.com/problems/where-will-the-ball-fall/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on |
| 7 | + * the top and bottom sides. |
| 8 | + * |
| 9 | + * Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a |
| 10 | + * ball to the right or to the left. |
| 11 | + * - A board that redirects the ball to the right spans the top-left corner to the bottom-right |
| 12 | + * corner and is represented in the grid as 1. |
| 13 | + * - A board that redirects the ball to the left spans the top-right corner to the bottom-left |
| 14 | + * corner and is represented in the grid as -1. |
| 15 | + * |
| 16 | + * We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall |
| 17 | + * out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a |
| 18 | + * board redirects the ball into either wall of the box. |
| 19 | + * |
| 20 | + * Return an array answer of size n where answer[i] is the column that the ball falls out of at the |
| 21 | + * bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in |
| 22 | + * the box. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number[][]} grid |
| 27 | + * @return {number[]} |
| 28 | + */ |
| 29 | +var findBall = function(grid) { |
| 30 | + const m = grid.length; |
| 31 | + const n = grid[0].length; |
| 32 | + const result = new Array(n); |
| 33 | + |
| 34 | + for (let col = 0; col < n; col++) { |
| 35 | + let currentCol = col; |
| 36 | + let row = 0; |
| 37 | + |
| 38 | + while (row < m) { |
| 39 | + const nextCol = currentCol + grid[row][currentCol]; |
| 40 | + |
| 41 | + if (nextCol < 0 || nextCol >= n || grid[row][currentCol] !== grid[row][nextCol]) { |
| 42 | + currentCol = -1; |
| 43 | + break; |
| 44 | + } |
| 45 | + |
| 46 | + currentCol = nextCol; |
| 47 | + row++; |
| 48 | + } |
| 49 | + |
| 50 | + result[col] = currentCol; |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +}; |
0 commit comments