2069. Walking Robot Simulation II


Problem Description

Given a robot that starts at the origin position (0,0) and has a width and height associated with it, the robot is required to be able to move through a grid in a defined pattern. Initially, the robot moves in a round trip fashion, going from the origin position to the last position in the same row, then from the last position in a column to the last position in the last row, and finally back to the origin position, completing the cycle.

The robot should be able to move num steps, and after moving the given number of steps, it should return its current position and direction.

Walkthrough

Let's start with an example, given a robot with width = 4 and height = 3, the grid would look like this:

1
2
30--1--2--3
4|       |
511--10--9
6|       |
712->7--6--5

The robot starts at position 0,0 and moves through the path as shown above. It should be able to perform steps and return the current position and direction.

Approach

The solution provided uses a vector of pairs, where each pair represents the position of the robot and the direction it is facing at that position. The solution initializes the pos vector by pushing the positions and directions during the construction of the robot object.

The step() function increases the index i of the pos vector by the given number of steps modulo the total number of positions in the vector.

The getPos() function returns the current position of the robot, and the getDir() function returns the current direction of the robot.

ASCII Illustration

1
2
30--1--2--3
4|       |
511--10--9
6|       |
712->7--6--5

Example:

  1. Robot initialized with width = 4 and height = 3, it starts at position (0, 0) and facing 'South'.
  2. Robot performs step(3), it moves to position (3, 0) and faces 'North'.
  3. Robot performs step(5), it moves to position (0, 2) and faces 'South'.

Solutions

Python Solution

1
2python
3class Solution:
4    def __init__(self, width, height):
5        self.pos = [((0, 0), "South")]
6        for i in range(1, width):
7            self.pos.append(((i, 0), "East"))
8        for j in range(1, height):
9            self.pos.append(((width - 1, j), "North"))
10        for i in range(width - 2, -1, -1):
11            self.pos.append(((i, height - 1), "West"))
12        for j in range(height - 2, 0, -1):
13            self.pos.append(((0, j), "South"))
14        self.i = 0
15        self.isOrigin = True
16
17    def step(self, num):
18        self.isOrigin = False
19        self.i = (self.i + num) % len(self.pos)
20
21    def getPos(self):
22        return self.pos[self.i][0]
23
24    def getDir(self):
25        return "East" if self.isOrigin else self.pos[self.i][1]

Java Solution

1
2java
3import java.util.ArrayList;
4import java.util.Arrays;
5
6public class Solution {
7    private ArrayList<int[]> pos;
8    private String[] dir;
9    private int i;
10    private boolean isOrigin;
11
12    public Solution(int width, int height) {
13        pos = new ArrayList<>();
14        dir = new String[width * 2 + height * 2 - 4];
15        pos.add(new int[]{0, 0});
16        dir[0] = "South";
17        int k = 1;
18        for (int i = 1; i < width; i++) {
19            pos.add(new int[]{i, 0});
20            dir[k++] = "East";
21        }
22        for (int j = 1; j < height; j++) {
23            pos.add(new int[]{width - 1, j});
24            dir[k++] = "North";
25        }
26        for (int i = width - 2; i >= 0; i--) {
27            pos.add(new int[]{i, height - 1});
28            dir[k++] = "West";
29        }
30        for (int j = height - 2; j > 0; j--) {
31            pos.add(new int[]{0, j});
32            dir[k++] = "South";
33        }
34        isOrigin = true;
35        i = 0;
36    }
37
38    public void step(int num) {
39        isOrigin = false;
40        i = (i + num) % pos.size();
41    }
42
43    public int[] getPos() {
44        return pos.get(i);
45    }
46
47    public String getDir() {
48        return isOrigin ? "East" : dir[i];
49    }
50}

JavaScript Solution

1
2javascript
3class Solution {
4  constructor(width, height) {
5    this.pos = [];
6    this.isOrigin = true;
7    this.i = 0;
8    this.pos.push([[0, 0], "South"]);
9    for (let i = 1; i < width; ++i)
10      this.pos.push([[i, 0], "East"]);
11    for (let j = 1; j < height; ++j)
12      this.pos.push([[width - 1, j], "North"]);
13    for (let i = width - 2; i >= 0; --i)
14      this.pos.push([[i, height - 1], "West"]);
15    for (let j = height - 2; j > 0; --j)
16      this.pos.push([[0, j], "South"]);
17  }
18
19  step(num) {
20    this.isOrigin = false;
21    this.i = (this.i + num) % this.pos.length;
22  }
23
24  getPos() {
25    return this.pos[this.i][0];
26  }
27
28  getDir() {
29    return this.isOrigin ? "East" : this.pos[this.i][1];
30  }
31}

C++ Solution

1
2cpp
3#include <vector>
4#include <string>
5using namespace std;
6
7class Solution {
8public:
9  Solution(int width, int height) {
10    pos.push_back({{0, 0}, "South"});
11    for (int i = 1; i < width; ++i)
12      pos.push_back({{i, 0}, "East"});
13    for (int j = 1; j < height; ++j)
14      pos.push_back({{width - 1, j}, "North"});
15    for (int i = width - 2; i >= 0; --i)
16      pos.push_back({{i, height - 1}, "West"});
17    for (int j = height - 2; j > 0; --j)
18      pos.push_back({{0, j}, "South"});
19    isOrigin = true;
20    i = 0;
21  }
22
23  void step(int num) {
24    isOrigin = false;
25    i = (i + num) % pos.size();
26  }
27
28  vector<int> getPos() {
29    return pos[i].first;
30  }
31
32  string getDir() {
33    return isOrigin ? "East" : pos[i].second;
34  }
35
36private:
37  bool isOrigin;
38  int i;
39  vector<pair<vector<int>, string>> pos;
40};

C# Solution

1
2csharp
3using System;
4using System.Collections.Generic;
5
6public class Solution {
7    private List<Tuple<int[], string>> pos;
8    private bool isOrigin;
9    private int i;
10
11    public Solution(int width, int height) {
12        pos = new List<Tuple<int[], string>>();
13        pos.Add(Tuple.Create(new int[]{0, 0}, "South"));
14        for (int i = 1; i < width; ++i) {
15            pos.Add(Tuple.Create(new int[]{i, 0}, "East"));
16        }
17        for (int j = 1; j < height; ++j) {
18            pos.Add(Tuple.Create(new int[]{width - 1, j}, "North"));
19        }
20        for (int i = width - 2; i >= 0; --i) {
21            pos.Add(Tuple.Create(new int[]{i, height - 1}, "West"));
22        }
23        for (int j = height - 2; j > 0; --j) {
24            pos.Add(Tuple.Create(new int[]{0, j}, "South"));
25        }
26        isOrigin = true;
27        i = 0;
28    }
29
30    public void Step(int num) {
31        isOrigin = false;
32        i = (i + num) % pos.Count;
33    }
34
35    public int[] GetPos() {
36        return pos[i].Item1;
37    }
38
39    public String GetDir() {
40        return isOrigin ? "East" : pos[i].Item2;
41    }
42}

Input and Output

The input for the given solutions is:

  1. A robot object is created using two integers width and height of the grid.

Example 1:

1
2python
3robot = Solution(4, 3)

Example 2:

1
2java
3Solution robot = new Solution(4, 3);
  1. The function step() is called for the given robot indicating the number of steps the robot should take.

Example 1:

1
2python
3robot.step(3)

Example 2:

1
2java
3robot.step(3);

The output for the given solutions consists of two functions:

  1. The function getPos() returns the current position of the robot in the form of a pair (tuple in python, int[] in Java, array in JavaScript, vector in C++, int[] in C#).

Example 1:

1
2python
3robot.getPos()

Example 2:

1
2java
3robot.getPos();
  1. The function getDir() returns the current direction of the robot in the form of a string.

Example 1:

1
2python
3robot.getDir()

Example 2:

1
2java
3robot.getDir();

These given solutions return the correct output, and the problem can be solved efficiently for the given constraints.

Examples

Example 1:

Robot created with width = 4, height = 3, and starting position (0, 0) facing South.

Input:

1
2python
3robot = Solution(4, 3)
4robot.getPos()
5robot.getDir()

Output:

1
2python
3(0, 0)
4"South"

Example 2:

Robot performs step(3) and moves to position (3, 0) facing North.

Input:

1
2python
3robot.step(3)
4robot.getPos()
5robot.getDir()

Output:

1
2python
3(3, 0)
4"North"

Example 3:

Robot performs step(5) and moves to position (0, 2) facing South.

Input:

1
2python
3robot.step(5)
4robot.getPos()
5robot.getDir()

Output:

1
2python
3(0, 2)
4"South"

The given solutions are efficient, and the problem can be solved using these methods in Python, Java, JavaScript, C++, and C#.

Not Sure What to Study? Take the 2-min Quiz to Find Your Missing Piece:

Which of the tree traversal order can be used to obtain elements in a binary search tree in sorted order?

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

Which data structure is used in a depth first search?

Solution Implementation

Not Sure What to Study? Take the 2-min Quiz:

Which two pointer techniques do you use to check if a string is a palindrome?

Fast Track Your Learning with Our Quick Skills Quiz:

How many times is a tree node visited in a depth first search?


Recommended Readings


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫