Skip to content

Commit

Permalink
Merge pull request #491 from HuangFuSL/leetcode-250215
Browse files Browse the repository at this point in the history
Update: Leetcode 250215
  • Loading branch information
github-actions[bot] authored Feb 15, 2025
2 parents 1e68177 + 920199d commit 7795783
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/coding/leetcode/.pages
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ nav:
- 1601-1650:
- 1603. 设计停车系统: 1603.md
- 1751-1800:
- 1706. 球会落何处: 1706.md
- 1742. 盒子中小球的最大数量: 1742.md
- 1760. 袋子里最少数目的球: 1760.md
- 1801-1850:
Expand Down
98 changes: 98 additions & 0 deletions docs/coding/leetcode/1706.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
---
tags:
- 数组
- 矩阵
- 模拟
category: leetcode
difficulty: 简单
---

# 1706. 球会落何处

{{ display_difficulty(page.meta.difficulty) }}

## 题目

用一个大小为 `m x n` 的二维网格 `grid` 表示一个箱子。你有 `n` 颗球。箱子的顶部和底部都是开着的。

箱子中的每个单元格都有一个对角线挡板,跨过单元格的两个角,可以将球导向左侧或者右侧。

* 将球导向右侧的挡板跨过左上角和右下角,在网格中用 `1` 表示。
* 将球导向左侧的挡板跨过右上角和左下角,在网格中用 `-1` 表示。

在箱子每一列的顶端各放一颗球。每颗球都可能卡在箱子里或从底部掉出来。如果球恰好卡在两块挡板之间的 "V" 形图案,或者被一块挡导向到箱子的任意一侧边上,就会卡住。

返回一个大小为 `n` 的数组 `answer` ,其中 `answer[i]` 是球放在顶部的第 `i` 列后从底部掉出来的那一列对应的下标,如果球卡在盒子里,则返回 `-1`

**示例 1:**

![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/12/26/ball.jpg)

> 输入:`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]]`
>
> 输出:`[1,-1,-1,-1,-1]`
>
> 解释:示例如图:
>
> b0 球开始放在第 0 列上,最终从箱子底部第 1 列掉出。
>
> b1 球开始放在第 1 列上,会卡在第 2、3 列和第 1 行之间的 "V" 形里。
>
> b2 球开始放在第 2 列上,会卡在第 2、3 列和第 0 行之间的 "V" 形里。
>
> b3 球开始放在第 3 列上,会卡在第 2、3 列和第 0 行之间的 "V" 形里。
>
> b4 球开始放在第 4 列上,会卡在第 2、3 列和第 1 行之间的 "V" 形里。
**示例 2:**

> 输入:`grid = [[-1]]`
>
> 输出:`[-1]`
>
> 解释:球被卡在箱子左侧边上。
**示例 3:**

> 输入:`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]]`
>
> 输出:`[0,1,2,3,4,-1]`
**提示:**

* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]``1``-1`

[Reference](https://leetcode.cn/problems/where-will-the-ball-fall)

## 题解

逐列模拟小球的行为,当小球处于`i``j`列位置时,小球下一次所在的列为`j + grid[i][j]`。当出现以下条件时,小球不能移动:

* `j + grid[i][j]`小于`0`或大于等于`len(grid[0])`(总列数),此时小球会被边界卡住。
* `grid[i][j]``j + grid[i][j]`符号不同,此时说明隔板构成一个V型凹槽卡住小球。

当以上两个条件都通过时,小球可以向下移动到`i + 1``j + grid[i][j]`列处,重复以上过程直到小球离开盒子或小球卡住。

```python
class Solution:
def simulate(self, grid: List[List[int]], currentCol: int) -> int:
currentRow, height, width = 0, len(grid), len(grid[0])
while currentRow < height:
nextCol = currentCol + grid[currentRow][currentCol]
if nextCol < 0 or nextCol >= width:
return -1
if grid[currentRow][currentCol] != grid[currentRow][nextCol]:
return -1
currentRow += 1
currentCol = nextCol
return currentCol

def findBall(self, grid: List[List[int]]) -> List[int]:
return [
self.simulate(grid, i)
for i in range(len(grid[0]))
]
```

0 comments on commit 7795783

Please sign in to comment.