Skip to content

2069. Walking Robot Simulation II 👎

  • Time: Constructor: $O(\texttt{width} + \texttt{height})$, step(num: int), getPos(), getDir(): $O(1)$
  • Space: $O(\texttt{width} + \texttt{height})$
 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
class Robot {
 public:
  Robot(int width, int height) {
    pos.push_back({{0, 0}, "South"});
    for (int i = 1; i < width; ++i)
      pos.push_back({{i, 0}, "East"});
    for (int j = 1; j < height; ++j)
      pos.push_back({{width - 1, j}, "North"});
    for (int i = width - 2; i >= 0; --i)
      pos.push_back({{i, height - 1}, "West"});
    for (int j = height - 2; j > 0; --j)
      pos.push_back({{0, j}, "South"});
  }

  void step(int num) {
    isOrigin = false;
    i = (i + num) % pos.size();
  }

  vector<int> getPos() {
    return pos[i].first;
  }

  string getDir() {
    return isOrigin ? "East" : pos[i].second;
  }

 private:
  bool isOrigin = true;
  int i = 0;
  vector<pair<vector<int>, string>> pos;
};
 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
class Robot {
  public Robot(int width, int height) {
    pos.add(new Pair<>(new int[] {0, 0}, "South"));
    for (int i = 1; i < width; ++i)
      pos.add(new Pair<>(new int[] {i, 0}, "East"));
    for (int j = 1; j < height; ++j)
      pos.add(new Pair<>(new int[] {width - 1, j}, "North"));
    for (int i = width - 2; i >= 0; --i)
      pos.add(new Pair<>(new int[] {i, height - 1}, "West"));
    for (int j = height - 2; j > 0; --j)
      pos.add(new Pair<>(new int[] {0, j}, "South"));
  }

  public void step(int num) {
    isOrigin = false;
    i = (i + num) % pos.size();
  }

  public int[] getPos() {
    return pos.get(i).getKey();
  }

  public String getDir() {
    return isOrigin ? "East" : pos.get(i).getValue();
  }

  private boolean isOrigin = true;
  private int i = 0;
  private List<Pair<int[], String>> pos = new ArrayList<>();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Robot:
  def __init__(self, width: int, height: int):
    self.isOrigin = True
    self.i = 0
    self.pos = [((0, 0), 'South')] + \
        [((i, 0), 'East') for i in range(1, width)] + \
        [((width - 1, j), 'North') for j in range(1, height)] + \
        [((i, height - 1), 'West') for i in range(width - 2, -1, -1)] +\
        [((0, j), 'South') for j in range(height - 2, 0, -1)]

  def step(self, num: int) -> None:
    self.isOrigin = False
    self.i = (self.i + num) % len(self.pos)

  def getPos(self) -> List[int]:
    return self.pos[self.i][0]

  def getDir(self) -> str:
    return 'East' if self.isOrigin else self.pos[self.i][1]
Back to top