[LeetCode] Check if Point Is Reachable

2543. Check if Point Is Reachable

There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.

In one step, you can move from point (x, y) to any one of the following points:

  • (x, y - x)
  • (x - y, y)
  • (2 * x, y)
  • (x, 2 * y)

Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isReachable(int x, int y) {
while(x != 1 or y != 1) {
while(x % 2 == 0) x /= 2;
while(y % 2 == 0) y /= 2;
if(x == 1 or y == 1) break;
if(x == y) return false;
if(x > y) x -= y;
else y -= x;
}
return x == 1 or y == 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/21/PS/LeetCode/check-if-point-is-reachable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.