#2069

Walking Robot Simulation II

expert · 1205 · lc medium +32 · 25.6% accepted · 193 likes · top 4%

Description

A robot starts at (0, 0) facing "East" on a width x height grid. Each step, it advances one cell in its current direction; if out of bounds, it turns 90° counterclockwise and retries. Implement the Robot class:

- Robot(int width, int height) — initialize the grid.
- void step(int num) — move forward num steps.
- int[] getPos() — return current position [x, y].
- String getDir() — return current facing direction ("North", "East", "South", or "West").

Example 1:

Input
["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"]
[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
Output
[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]

Example 2:

Explanation
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.step(2); // It moves two steps East to (2, 0), and faces East.
robot.step(2); // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return [4, 0]
robot.getDir(); // return "East"
robot.step(2); // It moves one step East to (5, 0), and faces East.
// Moving the next step East would be out of bounds, so it turns and faces North.
// Then, it moves one step North to (5, 1), and faces North.
robot.step(1); // It moves one step North to (5, 2), and faces North (not West).
robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.
// Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return [1, 2]
robot.getDir(); // return "West"

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20