Skip to main content
Back to problems
#2069
Medium Algorithms

Walking robot simulation ii

Design Simulation
25.6% acceptance
Feb 25, 2026
193
321
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. Attempts to move forward one cell in the direction it is facing. 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".

Solution

Rust
Time O(1)
Space O(n)
LeetCode
solution.rs
struct Robot {
  width: i64,
  height: i64,
  pos: i64,
  perimeter: i64,
  moved: bool,
}

impl Robot {
  fn new(width: i32, height: i32) -> Self {
    let w = width as i64;
    let h = height as i64;
    let perimeter = 2 * (w - 1) + 2 * (h - 1);
    Robot { width: w, height: h, pos: 0, perimeter, moved: false }
  }

  fn step(&mut self, num: i32) {
    self.pos = (self.pos + num as i64) % self.perimeter;
    self.moved = true;
  }

  fn get_pos(&self) -> Vec<i32> {
    let p = self.pos;
    let w = self.width;
    let h = self.height;
    let (x, y) = if p < w {
      (p, 0)
    } else if p < w + h - 1 {
      (w - 1, p - w + 1)
    } else if p < 2 * w + h - 2 {
      (2 * w + h - 3 - p, h - 1)
    } else {
      (0, 2 * w + 2 * h - 4 - p)
    };
    vec![x as i32, y as i32]
  }

  fn get_dir(&self) -> String {
    if !self.moved {
      return "East".to_string();
    }
    let p = self.pos;
    let w = self.width;
    let h = self.height;
    let dir = if p == 0 {
      "South"
    } else if p < w {
      "East"
    } else if p < w + h - 1 {
      "North"
    } else if p < 2 * w + h - 2 {
      "West"
    } else {
      "South"
    };
    dir.to_string()
  }
}