forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walking-robot-simulation-ii.cpp
94 lines (81 loc) · 1.84 KB
/
walking-robot-simulation-ii.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Time: O(1)
// Space: O(1)
class Robot {
public:
Robot(int width, int height) : w_(width), h_(height) {
}
void move(int num) {
curr_ += num;
}
vector<int> getPos() {
int n = curr_ % (2 * ((w_ - 1) + h_ - 1));
if (n < w_) {
return {n, 0};
}
n -= (w_ - 1);
if (n < h_) {
return {w_ - 1, n};
}
n -= (h_ - 1);
if (n < w_) {
return {(w_ - 1) - n, h_ - 1};
}
n -= (w_ - 1);
return {0, (h_ - 1) - n};
}
string getDir() {
int n = curr_ % (2 * ((w_ - 1) + h_ - 1));
if (n < w_) {
return n == 0 && curr_ ? "South" : "East";
}
n -= (w_ - 1);
if (n < h_) {
return "North";
}
n -= (h_ - 1);
if (n < w_) {
return "West";
}
n -= (w_ - 1);
return "South";
}
const int w_;
const int h_;
int curr_ = 0;
};
// Time: O(1)
// Space: O(1)
class Robot2 {
public:
Robot2(int width, int height) : w_(width), h_(height) {
}
void move(int num) {
curr_ += num;
}
vector<int> getPos() {
return getPosDir().first;
}
string getDir() {
return getPosDir().second;
}
private:
pair<vector<int>, string> getPosDir() {
int n = curr_ % (2 * ((w_ - 1) + h_ - 1));
if (n < w_) {
return {{n, 0}, (n == 0 && curr_) ? "South" : "East"};
}
n -= (w_ - 1);
if (n < h_) {
return {{w_ - 1, n}, "North"};
}
n -= (h_ - 1);
if (n < w_) {
return {{(w_ - 1) - n, h_ - 1}, "West"};
}
n -= (w_ - 1);
return {{0, (h_ - 1) - n}, "South"};
}
const int w_;
const int h_;
int curr_ = 0;
};