-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathminimum-moves-to-reach-target-in-grid.cpp
More file actions
44 lines (43 loc) · 1.09 KB
/
minimum-moves-to-reach-target-in-grid.cpp
File metadata and controls
44 lines (43 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Time: O(logtx + logty)
// Space: O(1)
// backward simulation
class Solution {
public:
int minMoves(int sx, int sy, int tx, int ty) {
int result = 0;
while (sx != tx || sy != ty) {
if (!(sx <= tx && sy <= ty)) {
return -1;
}
if (tx < ty) {
if (tx > ty - tx) {
ty -= tx;
} else {
if (ty % 2) {
return -1;
}
ty -= ty / 2;
}
} else if (tx > ty) {
if (ty > tx - ty) {
tx -= ty;
} else {
if (tx % 2) {
return -1;
}
tx -= tx / 2;
}
} else {
if (sx == 0) {
tx -= ty;
} else if (sy == 0) {
ty -= tx;
} else {
return -1;
}
}
++result;
}
return result;
}
};