LeetCode 780. Reaching Points
原题链接
困难
作者:
JasonSun
,
2020-02-20 11:34:08
,
所有人可见
,
阅读 846
Algorithm (Euclidean Algorithm)
- Searching from the starting point is not easy because at each step there are two decisions, the number of nodes in the next level grows exponentially but we don’t have a clear criterion to help us prune the search.
- However, on the other hand working from the backward proves to be easier since for each node has an unique parent: for a node $(x,y)$, one could check that $$\text{parent}(x,y)=\begin{cases}
(x+y-\max(x,y),2\cdot\max(x,y)-(x+y)) & \text{if }y\geq x\\\\
(2\cdot\max(x,y)-(x+y),x+y-\max(x,y)) & \text{if }y<x
\end{cases}$$
- This suggests we could traverse backward up to see if $(s_{x},s_{y})$ is in our search path. Doing so with bruteforce would result in TLE; therefore we use modulo operations to speed up the backward search process: if $x\geq y$ then the next node we search is $(x\mod y,y),$ this is because $x=x_{n-1}+y=x_{n-2}+y+y=…=x_{1}+ky$ for some $x_{1}\geq0$. Using modulo, we can directly calculate $x_{1}$ instead of $x_{n-1}.$ The same trick applies to $y$ as well.
- The rest is formality. The idea of this solution is based on
wzc
‘s original post. All credit goes to him~
Code (Cpp17)
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
std::function<bool(int, int)> go = [&](int x, int y) {
if (x < sx or y < sy)
return false;
else if (x == sx)
return (y - sy) % sx == 0;
else if (y == sy)
return (x - sx) % sy == 0;
else
return x >= y ? go(x % y, y) : go(x, y % x);
};
return go(tx, ty);
}
};