LeetCode 题解工作台
判断一个点是否可以到达
给你一个无穷大的网格图。一开始你在 (1, 1) ,你需要通过有限步移动到达点 (targetX, targetY) 。 每一步 ,你可以从点 (x, y) 移动到以下点之一: (x, y - x) (x - y, y) (2 * x, y) (x, 2 * y) 给你两个整数 targetX 和 …
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数学·结合·number·theory
答案摘要
我们注意到,前两种移动方式不会改变横、纵坐标的最大公约数,而后两种移动方式可以使得横、纵坐标的最大公约数乘上 的幂次。也就是说,最后的横、纵坐标的最大公约数必须是 的幂次。最大公约数不是 的幂次,那么就无法到达。 接下来,我们证明,任意满足 $gcd(x, y)=2^k$ 的 $(x, y)$ 均可达。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·number·theory 题型思路
题目描述
给你一个无穷大的网格图。一开始你在 (1, 1) ,你需要通过有限步移动到达点 (targetX, targetY) 。
每一步 ,你可以从点 (x, y) 移动到以下点之一:
(x, y - x)(x - y, y)(2 * x, y)(x, 2 * y)
给你两个整数 targetX 和 targetY ,分别表示你最后需要到达点的 X 和 Y 坐标。如果你可以从 (1, 1) 出发到达这个点,请你返回true ,否则返回 false 。
示例 1:
输入:targetX = 6, targetY = 9 输出:false 解释:没法从 (1,1) 出发到达 (6,9) ,所以返回 false 。
示例 2:
输入:targetX = 4, targetY = 7 输出:true 解释:你可以按照以下路径到达:(1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7) 。
提示:
1 <= targetX, targetY <= 109
解题思路
方法一:数学
我们注意到,前两种移动方式不会改变横、纵坐标的最大公约数,而后两种移动方式可以使得横、纵坐标的最大公约数乘上 的幂次。也就是说,最后的横、纵坐标的最大公约数必须是 的幂次。最大公约数不是 的幂次,那么就无法到达。
接下来,我们证明,任意满足 的 均可达。
我们将移动方式反转一下,即从终点往回走,那么 可以移动到 , , 和 。
只要 或 是偶数,我们就将其除以 ,直到 和 均为奇数。此时,若 ,不妨设 ,那么 。由于 是偶数,我们可以通过操作从 移动到 ,再移动到 。也就是说,我们总能让 和 不断变小。循环结束时,如果 ,说明可以到达。
时间复杂度 ,空间复杂度 。
class Solution:
def isReachable(self, targetX: int, targetY: int) -> bool:
x = gcd(targetX, targetY)
return x & (x - 1) == 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on how many reverse operations are applied. In the worst case, each step roughly halves a coordinate or subtracts values, giving logarithmic bounds, but exact performance varies with the input pattern. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate attempting a reverse approach from target to origin.
- question_mark
Watch for correct handling of even and odd coordinate cases using number theory.
- question_mark
Assess whether the solution avoids unnecessary recursion and infinite loops.
常见陷阱
外企场景- error
Trying only forward moves from (1,1) leads to excessive search space.
- error
Ignoring parity and GCD constraints can cause incorrect true results.
- error
Failing to stop recursion or loops when coordinates cannot reduce causes infinite computation.
进阶变体
外企场景- arrow_right_alt
Determine reachability on a grid where moves allow multiplication or division by 3 instead of 2.
- arrow_right_alt
Find the minimum number of steps required to reach a target point using the same move rules.
- arrow_right_alt
Check reachability with additional diagonal moves combining x and y increments.