Minimum Moves to Reach Target in Grid Problem
Description
LeetCode Problem 3609.
You are given four integers sx, sy, tx, and ty, representing two points (sx, sy) and (tx, ty) on an infinitely large 2D grid.
You start at (sx, sy).
At any point (x, y), define m = max(x, y). You can either:
- Move to
(x + m, y), or - Move to
(x, y + m).
Return the minimum number of moves required to reach (tx, ty). If it is impossible to reach the target, return -1.
Example 1:
Input: sx = 1, sy = 2, tx = 5, ty = 4
Output: 2
Explanation:
The optimal path is:
- Move 1: max(1, 2) = 2. Increase the y-coordinate by 2, moving from (1, 2) to (1, 2 + 2) = (1, 4).
- Move 2: max(1, 4) = 4. Increase the x-coordinate by 4, moving from (1, 4) to (1 + 4, 4) = (5, 4).
Thus, the minimum number of moves to reach (5, 4) is 2.
Example 2:
Input: sx = 0, sy = 1, tx = 2, ty = 3
Output: 3
Explanation:
The optimal path is:
- Move 1: max(0, 1) = 1. Increase the x-coordinate by 1, moving from (0, 1) to (0 + 1, 1) = (1, 1).
- Move 2: max(1, 1) = 1. Increase the x-coordinate by 1, moving from (1, 1) to (1 + 1, 1) = (2, 1).
- Move 3: max(2, 1) = 2. Increase the y-coordinate by 2, moving from (2, 1) to (2, 1 + 2) = (2, 3).
Thus, the minimum number of moves to reach (2, 3) is 3.
Example 3:
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: -1
Explanation:
- It is impossible to reach (2, 2) from (1, 1) using the allowed moves. Thus, the answer is -1.
Constraints:
0 <= sx <= tx <= 10^90 <= sy <= ty <= 10^9
Solution
Approach: Work Backwards
The coordinates reach 10^9, so searching forward is hopeless, but a move can be undone almost uniquely. Walk back from (tx, ty) towards (sx, sy).
If x < y, the last move must have added to y (adding to x would have made x at least y). Before it, either y' >= x, which forces y = 2y', or y' < x, which means y = y' + x. These cases cannot both hold: if y < 2x the previous y is y - x, otherwise y must be even and the previous y is y / 2. The case x > y is symmetric. Every step shrinks the larger coordinate quickly (it is halved or behaves like a Euclid step), so there are only O(log) steps.
The one ambiguous state is x == y > 0. Then the previous state must be (0, x) or (x, 0) (a point with a zero coordinate moves to (m, m)), so we try both. We stop with -1 when a coordinate falls below the start or when we reach (0, 0) that is not the start.
Complexity: O(log(max(tx, ty))) time and space.
class Solution:
def minMoves(self, sx: int, sy: int, tx: int, ty: int) -> int:
def dfs(x, y):
if x == sx and y == sy:
return 0
if x < sx or y < sy or (x == 0 and y == 0):
return -1
if x == y:
res = [v for v in (dfs(0, x), dfs(x, 0)) if v >= 0]
return min(res) + 1 if res else -1
if x < y:
if y < 2 * x:
r = dfs(x, y - x)
elif y % 2 == 0:
r = dfs(x, y // 2)
else:
return -1
else:
if x < 2 * y:
r = dfs(x - y, y)
elif x % 2 == 0:
r = dfs(x // 2, y)
else:
return -1
return r + 1 if r >= 0 else -1
return dfs(tx, ty)