Walking Robot Simulation

medium array simulation hash table

Problem

A robot starts at (0, 0) facing north. Commands: −2 turn left 90°, −1 turn right 90°, and 1 ≤ k ≤ 9 move forward k units (stopping just before any obstacle). Return the maximum squared Euclidean distance from the origin the robot ever reaches.

Inputcommands = [4,-1,3], obstacles = []
Output25
Moves to (0,4), turns right, moves to (3,4): 3² + 4² = 25.

def robot_sim(commands, obstacles):
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]   # N, E, S, W
    d = 0
    x = y = best = 0
    blocked = {tuple(o) for o in obstacles}
    for c in commands:
        if c == -2:
            d = (d - 1) % 4
        elif c == -1:
            d = (d + 1) % 4
        else:
            for _ in range(c):
                nx, ny = x + dx[d], y + dy[d]
                if (nx, ny) in blocked:
                    break
                x, y = nx, ny
                best = max(best, x * x + y * y)
    return best
function robotSim(commands, obstacles) {
  const dx = [0, 1, 0, -1], dy = [1, 0, -1, 0]; // N, E, S, W
  let d = 0, x = 0, y = 0, best = 0;
  const blocked = new Set(obstacles.map(o => o[0] + "," + o[1]));
  for (const c of commands) {
    if (c === -2) d = (d + 3) % 4;
    else if (c === -1) d = (d + 1) % 4;
    else for (let s = 0; s < c; s++) {
      const nx = x + dx[d], ny = y + dy[d];
      if (blocked.has(nx + "," + ny)) break;
      x = nx; y = ny;
      best = Math.max(best, x * x + y * y);
    }
  }
  return best;
}
int robotSim(int[] commands, int[][] obstacles) {
    int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
    int d = 0, x = 0, y = 0, best = 0;
    Set<Long> blocked = new HashSet<>();
    for (int[] o : obstacles) blocked.add(o[0] * 100000L + o[1]);
    for (int c : commands) {
        if (c == -2) d = (d + 3) % 4;
        else if (c == -1) d = (d + 1) % 4;
        else for (int s = 0; s < c; s++) {
            int nx = x + dx[d], ny = y + dy[d];
            if (blocked.contains(nx * 100000L + ny)) break;
            x = nx; y = ny;
            best = Math.max(best, x * x + y * y);
        }
    }
    return best;
}
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
    int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
    int d = 0, x = 0, y = 0, best = 0;
    set<pair<int,int>> blocked;
    for (auto& o : obstacles) blocked.insert({o[0], o[1]});
    for (int c : commands) {
        if (c == -2) d = (d + 3) % 4;
        else if (c == -1) d = (d + 1) % 4;
        else for (int s = 0; s < c; s++) {
            int nx = x + dx[d], ny = y + dy[d];
            if (blocked.count({nx, ny})) break;
            x = nx; y = ny;
            best = max(best, x * x + y * y);
        }
    }
    return best;
}
Time: O(commands · k) Space: O(obstacles)