[LeetCode] Walking Robot Simulation II

2069. Walking Robot Simulation II

A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions (“North”, “East”, “South”, and “West”). A robot is initially at cell (0, 0) facing direction “East”.

The robot can be instructed to move for a specific number of steps. For each step, it does the following.

  1. Attempts to move forward one cell in the direction it is facing.
  2. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.

After the robot finishes moving the number of steps required, it stops and awaits the next instruction.

Implement the Robot class:

  • Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing “East”.
  • void step(int num) Instructs the robot to move forward num steps.
  • int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
  • String getDir() Returns the current direction of the robot, “North”, “East”, “South”, or “West”.
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
class Robot {
int pos, w, h;
bool s;
public:
Robot(int width, int height): pos(0), w(width), h(height), s(false) {}

void step(int num) {
s = true;
pos = (pos + num) % ((w + h - 2) << 1);
}

vector<int> getPos() {
if(pos < w) return {pos, 0};
if(pos < w + h - 1) return {w - 1, pos - w + 1};
if(pos < 2 * w + h - 2) return {w - 1 - (pos - w - h + 2), h - 1};
return {0, h - 1 - (pos - 2 * w - h + 3)};
}

string getDir() {
if(pos < w) return !pos and s ? "South" : "East";
if(pos < w + h - 1) return "North";
if(pos < 2 * w + h - 2) return "West";
return "South";
}
};

/**
* Your Robot object will be instantiated and called as such:
* Robot* obj = new Robot(width, height);
* obj->step(num);
* vector<int> param_2 = obj->getPos();
* string param_3 = obj->getDir();
*/

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/14/PS/LeetCode/walking-robot-simulation-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.