Sponsored
Sponsored
Simulate the movement of the robot by maintaining a variable for the current direction. Use an array to store the possible directions: north, east, south, and west. When a turn command is received, adjust the direction index. For movement commands, move the robot in the direction indexed by the current direction.
Time Complexity: O(N + M), where N is the number of commands and M is the number of obstacles.
Space Complexity: O(M), where M is the number of obstacles.
1import java.util.HashSet;
2import java.util.Set;
3
4public class Robot {
5 public int robotSim(int[] commands, int[][] obstacles) {
6 Set<String> obstacleSet = new HashSet<>();
7 for (int[] obs : obstacles) {
8 obstacleSet.add(obs[0] + "," + obs[1]);
9 }
10
11 int[] dx = {0, 1, 0, -1};
12 int[] dy = {1, 0, -1, 0};
13 int x = 0, y = 0, direction = 0, maxDistSq = 0;
14
15 for (int cmd : commands) {
16 if (cmd == -2) { // Turn left
17 direction = (direction + 3) % 4;
18 } else if (cmd == -1) { // Turn right
19 direction = (direction + 1) % 4;
20 } else {
21 for (int k = 0; k < cmd; k++) {
22 int nx = x + dx[direction];
23 int ny = y + dy[direction];
24 if (!obstacleSet.contains(nx + "," + ny)) {
25 x = nx;
26 y = ny;
27 maxDistSq = Math.max(maxDistSq, x * x + y * y);
28 } else {
29 break;
30 }
31 }
32 }
33 }
34
35 return maxDistSq;
36 }
37}
In Java, the solution leverages a HashSet to handle obstacle lookups, utilizing a specific string format to store coordinates. Directions are handled using arrays, and the robot's movement is tracked by updating coordinates. Distance is calculated and stored as the robot moves.