LeetCode 题解工作台
判断能否在给定时间到达单元格
给你四个整数 sx 、 sy 、 fx 、 fy 以及一个 非负整数 t 。 在一个无限的二维网格中,你从单元格 (sx, sy) 开始出发。每一秒,你 必须 移动到任一与之前所处单元格相邻的单元格中。 如果你能在 恰好 t 秒 后到达单元格 (fx, fy) ,返回 true ;否则,返回 fal…
1
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数学·driven
答案摘要
如果起点和终点相同,那么只有当 $t \neq 1$ 时,才能在给定时间到达终点。 否则,我们可以计算出起点和终点的横纵坐标之差,然后取最大值,如果最大值小于等于给定时间,那么就可以在给定时间到达终点。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你四个整数 sx、sy、fx、fy 以及一个 非负整数 t 。
在一个无限的二维网格中,你从单元格 (sx, sy) 开始出发。每一秒,你 必须 移动到任一与之前所处单元格相邻的单元格中。
如果你能在 恰好 t 秒 后到达单元格 (fx, fy) ,返回 true ;否则,返回 false 。
单元格的 相邻单元格 是指该单元格周围与其至少共享一个角的 8 个单元格。你可以多次访问同一个单元格。
示例 1:
输入:sx = 2, sy = 4, fx = 7, fy = 7, t = 6 输出:true 解释:从单元格 (2, 4) 开始出发,穿过上图标注的单元格,可以在恰好 6 秒后到达单元格 (7, 7) 。
示例 2:
输入:sx = 3, sy = 1, fx = 7, fy = 3, t = 3 输出:false 解释:从单元格 (3, 1) 开始出发,穿过上图标注的单元格,至少需要 4 秒后到达单元格 (7, 3) 。 因此,无法在 3 秒后到达单元格 (7, 3) 。
提示:
1 <= sx, sy, fx, fy <= 1090 <= t <= 109
解题思路
方法一:分情况讨论
如果起点和终点相同,那么只有当 时,才能在给定时间到达终点。
否则,我们可以计算出起点和终点的横纵坐标之差,然后取最大值,如果最大值小于等于给定时间,那么就可以在给定时间到达终点。
时间复杂度 ,空间复杂度 。
class Solution:
def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool:
if sx == fx and sy == fy:
return t != 1
dx = abs(sx - fx)
dy = abs(sy - fy)
return max(dx, dy) <= t
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(1) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The candidate's ability to recognize and use the Manhattan distance in a 2D grid.
- question_mark
Checking the evenness of the difference between minimum time and t to ensure exact movement.
- question_mark
Efficiency in arriving at the correct result with minimal operations.
常见陷阱
外企场景- error
Forgetting to check if the difference between minimum time and t is even, which would lead to incorrect results.
- error
Misunderstanding that movement can be in any direction, requiring the use of Manhattan distance rather than Euclidean distance.
- error
Confusing the minimum time to reach the target with the exact time condition t.
进阶变体
外企场景- arrow_right_alt
Consider a problem where the time t is replaced by a time range and check if the target can be reached within that range.
- arrow_right_alt
Expand the grid to a 3D space, requiring adjustment to the movement calculations.
- arrow_right_alt
Introduce obstacles or constraints on movement that change the time calculation and test adaptability.