Skip to content

Commit 5f64d98

Browse files
feat: add C++ code for Walking Robot Simulation II (#5139)
Added C++ implementation of the Robot class with methods for stepping and getting position and direction. Leetcode 2069
1 parent 023ed13 commit 5f64d98

1 file changed

Lines changed: 44 additions & 1 deletion

File tree

  • solution/2000-2099/2069.Walking Robot Simulation II

solution/2000-2099/2069.Walking Robot Simulation II/README.md

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,50 @@ robot.getDir(); // 返回 "West"
102102
```
103103

104104
#### C++
105-
105+
#pragma GCC optimize("Ofast,unroll-loops,inline")
106+
#include <vector>
107+
#include <string>
108+
109+
static const int speedup = []() {
110+
std::ios_base::sync_with_stdio(false);
111+
std::cin.tie(NULL);
112+
return 0;
113+
}();
114+
115+
class Robot {
116+
int w, h, p, curr;
117+
bool moved;
118+
// Используем массив строк, чтобы обращаться по индексу (0-3) без if-else
119+
const std::string dirs[4] = {"East", "North", "West", "South"};
120+
121+
public:
122+
Robot(int width, int height) : w(width), h(height), curr(0), moved(false) {
123+
p = (w + h - 2) << 1;
124+
}
125+
126+
inline void step(int num) {
127+
moved = true;
128+
curr = (curr + num) % p;
129+
}
130+
131+
inline std::vector<int> getPos() {
132+
if (curr < w) return {curr, 0};
133+
if (curr < w + h - 1) return {w - 1, curr - w + 1};
134+
if (curr < (w << 1) + h - 2) return { (w << 1) + h - 3 - curr, h - 1};
135+
return {0, p - curr};
136+
}
137+
138+
inline std::string getDir() {
139+
if (!moved) return dirs[0];
140+
if (curr == 0) return dirs[3]; // Робот вернулся в начало — всегда South
141+
142+
// Математическое определение направления без тяжелых веток
143+
if (curr < w) return dirs[0];
144+
if (curr < w + h - 1) return dirs[1];
145+
if (curr < (w << 1) + h - 2) return dirs[2];
146+
return dirs[3];
147+
}
148+
};
106149
```cpp
107150

108151
```

0 commit comments

Comments
 (0)