Walking Robot Simulation Solution in Java

Explore Solutions in Other Languages

C++ Solution |
Python Solution

Code Solution


class Solution {
  public int robotSim(int[] commands, int[][] obstacles) {
    final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int ans = 0;
    int d = 0; // 0 := north, 1 := east, 2 := south, 3 := west
    int x = 0; // the start x
    int y = 0; // the start y
    Set> obstaclesSet = new HashSet<>();

    for (int[] obstacle : obstacles) {
      final int x_ = obstacle[0];
      final int y_ = obstacle[1];
      obstaclesSet.add(new Pair<>(x_, y_));
    }

    for (final int command : commands) {
      if (command == -1) {
        d = (d + 1) % 4;
      } else if (command == -2) {
        d = (d + 3) % 4;
      } else {
        for (int step = 0; step < command; ++step) {
          if (obstaclesSet.contains(new Pair<>(x + dirs[d][0], y + dirs[d][1])))
            break;
          x += dirs[d][0];
          y += dirs[d][1];
        }
      }
      ans = Math.max(ans, x * x + y * y);
    }

    return ans;
  }
}

Problem Description

So, you think you can control a robot? Well, welcome to the Walking Robot Simulation! Imagine a robot that can only follow your commands, but it’s as stubborn as a toddler. You give it a series of commands to move around a grid, but watch out! There are obstacles lurking around like that one friend who always gets in the way of your plans.

The robot starts at the origin (0, 0) and can face four directions: North, East, South, and West. You can tell it to move forward or turn left/right. But if it encounters an obstacle, it will stop moving forward, just like you would when you see your ex at a party.

Approach

The code provided simulates the robot’s movement based on the commands given. It maintains the robot’s current position and direction, checks for obstacles, and calculates the maximum distance squared from the origin after executing all commands. The robot can turn left or right, and it will stop moving if it encounters an obstacle.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N + M)
Space Complexity O(M)

Real-World Example

Think of this robot as a delivery drone trying to navigate through a busy neighborhood. You give it commands to deliver packages, but it has to avoid trees, power lines, and that one neighbor’s annoying cat that always seems to be in the way. Just like in the simulation, if the drone encounters an obstacle, it has to stop and find a new route, ensuring it delivers the package without crashing into anything.

Similar Problems

If you enjoyed this problem, you might also like these: