LeetCode 题解工作台
逃脱阻碍者
你在进行一个简化版的吃豆人游戏。你从 [0, 0] 点开始出发,你的目的地是 target = [x target , y target ] 。地图上有一些阻碍者,以数组 ghosts 给出,第 i 个阻碍者从 ghosts[i] = [x i , y i ] 出发。所有输入均为 整数坐标 。 每一…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
对于任意一个阻碍者,如果它到目的地的曼哈顿距离小于等于你到目的地的曼哈顿距离,那么它就可以在你到达目的地之前抓住你。因此,我们只需要判断所有阻碍者到目的地的曼哈顿距离是否都大于你到目的地的曼哈顿距离即可。 时间复杂度 ,空间复杂度 。其中 为阻碍者的数量。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
你在进行一个简化版的吃豆人游戏。你从 [0, 0] 点开始出发,你的目的地是 target = [xtarget, ytarget] 。地图上有一些阻碍者,以数组 ghosts 给出,第 i 个阻碍者从 ghosts[i] = [xi, yi] 出发。所有输入均为 整数坐标 。
每一回合,你和阻碍者们可以同时向东,西,南,北四个方向移动,每次可以移动到距离原位置 1 个单位 的新位置。当然,也可以选择 不动 。所有动作 同时 发生。
如果你可以在任何阻碍者抓住你 之前 到达目的地(阻碍者可以采取任意行动方式),则被视为逃脱成功。如果你和阻碍者 同时 到达了一个位置(包括目的地) 都不算 是逃脱成功。
如果不管阻碍者怎么移动都可以成功逃脱时,输出 true ;否则,输出 false 。
示例 1:
输入:ghosts = [[1,0],[0,3]], target = [0,1] 输出:true 解释:你可以直接一步到达目的地 (0,1) ,在 (1, 0) 或者 (0, 3) 位置的阻碍者都不可能抓住你。
示例 2:
输入:ghosts = [[1,0]], target = [2,0] 输出:false 解释:你需要走到位于 (2, 0) 的目的地,但是在 (1, 0) 的阻碍者位于你和目的地之间。
示例 3:
输入:ghosts = [[2,0]], target = [1,0] 输出:false 解释:阻碍者可以和你同时达到目的地。
提示:
1 <= ghosts.length <= 100ghosts[i].length == 2-104 <= xi, yi <= 104- 同一位置可能有 多个阻碍者 。
target.length == 2-104 <= xtarget, ytarget <= 104
解题思路
方法一:曼哈顿距离
对于任意一个阻碍者,如果它到目的地的曼哈顿距离小于等于你到目的地的曼哈顿距离,那么它就可以在你到达目的地之前抓住你。因此,我们只需要判断所有阻碍者到目的地的曼哈顿距离是否都大于你到目的地的曼哈顿距离即可。
时间复杂度 ,空间复杂度 。其中 为阻碍者的数量。
class Solution:
def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:
tx, ty = target
return all(abs(tx - x) + abs(ty - y) > abs(tx) + abs(ty) for x, y in ghosts)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for efficient handling of the distance calculation.
- question_mark
Check the approach to early exits and minimal computation.
- question_mark
Assess how the solution scales when more ghosts are added.
常见陷阱
外企场景- error
Misunderstanding the simultaneous movement of ghosts and the player.
- error
Incorrectly comparing distances by neglecting the Manhattan distance formula.
- error
Failing to optimize for early exits, potentially leading to slower solutions.
进阶变体
外企场景- arrow_right_alt
Incorporate dynamic grid changes where some obstacles appear along the path.
- arrow_right_alt
Introduce ghosts with different speeds and behavior patterns.
- arrow_right_alt
Adjust the problem to allow ghosts to react differently, such as following you.