KK's blog

每天积累多一些

0%

LeetCode 1706 Where Will the Ball Fall

LeetCode



You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.

Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.

A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1. A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.

We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a “V” shaped pattern between two boards or if a board redirects the ball into either wall of the box.

Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the i<sup>th</sup> _column at the top, or -1 if the ball gets stuck in the box._

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]
Explanation: 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]
Explanation: 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]


Constraints:

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

题目大意:

二维数组每一个cell都是1或者-1,分别表示一个玻璃板的放置方向,正对角线或者反对角线。球从每一个列投下,根据玻璃板的设置,若成功从底部滑出,输入列号,否则输入-1. 求这个结果数组。

解题思路:

这是Q&A题目。游戏模拟题大多用DFS,因为就是选择一条路径走到底。

解题步骤:

N/A

注意事项:

  1. 任何情况都是row + 1,而不是-1
  2. 题目要求若成功,输出球跌出的列号,而不是boolean = 1

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def findBall(self, grid: List[List[int]]) -> List[int]:
return [self.dfs(grid, 0, j) for j in range(len(grid[0]))]

def dfs(self, grid, row, col):
if row == len(grid):
return col
if grid[row][col] == 1:
if col + 1 == len(grid[0]) or grid[row][col + 1] == -1:
return -1
else:
return self.dfs(grid, row + 1, col + 1)
else:
if col - 1 < 0 or grid[row][col - 1] == 1:
return -1
else:
return self.dfs(grid, row + 1, col - 1)

算法分析:

时间复杂度为O(nm),空间复杂度O(1), n, m分别为行数和列数。

Free mock interview