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.
1function robotSim(commands, obstacles) {
2 const obstacleSet = new Set(obstacles.map(obs => obs.toString()));
3 const dx = [0, 1, 0, -1];
4 const dy = [1, 0, -1, 0];
5 let x = 0, y = 0, direction = 0, maxDistSq = 0;
6
7 for (const cmd of commands) {
8 if (cmd === -2) { // Turn left
9 direction = (direction + 3) % 4;
10 } else if (cmd === -1) { // Turn right
11 direction = (direction + 1) % 4;
12 } else {
13 for (let k = 0; k < cmd; k++) {
14 const nx = x + dx[direction];
15 const ny = y + dy[direction];
16 if (!obstacleSet.has([nx, ny].toString())) {
17 x = nx;
18 y = ny;
19 maxDistSq = Math.max(maxDistSq, x * x + y * y);
20 } else {
21 break;
22 }
23 }
24 }
25 }
26
27 return maxDistSq;
28}
The JavaScript solution utilizes a Set for quick access to obstacle positions, converting positions to string for storage. Directional changes are managed through modulated index values in directional arrays. Movement is adjusted based on the presence of obstacles, updating the squared distance as necessary.