|
| 1 | +/** |
| 2 | + * 874. Walking Robot Simulation |
| 3 | + * https://leetcode.com/problems/walking-robot-simulation/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array |
| 7 | + * of integers commands, which represents a sequence of moves that it needs to execute. There are |
| 8 | + * only three possible types of instructions the robot can receive: |
| 9 | + * - -2: Turn left 90 degrees. |
| 10 | + * - -1: Turn right 90 degrees. |
| 11 | + * - 1 <= k <= 9: Move forward k units, one unit at a time. |
| 12 | + * |
| 13 | + * Some of the grid squares are obstacles. The ith obstacle is at grid point |
| 14 | + * obstacles[i] = (xi, yi). If the robot runs into an obstacle, it will stay in its current location |
| 15 | + * (on the block adjacent to the obstacle) and move onto the next command. |
| 16 | + * |
| 17 | + * Return the maximum squared Euclidean distance that the robot reaches at any point in its path |
| 18 | + * (i.e. if the distance is 5, return 25). |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * - There can be an obstacle at (0, 0). If this happens, the robot will ignore the obstacle until |
| 22 | + * it has moved off the origin. However, it will be unable to return to (0, 0) due to the |
| 23 | + * obstacle. |
| 24 | + * - North means +Y direction. |
| 25 | + * - East means +X direction. |
| 26 | + * - South means -Y direction. |
| 27 | + * - West means -X direction. |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number[]} commands |
| 32 | + * @param {number[][]} obstacles |
| 33 | + * @return {number} |
| 34 | + */ |
| 35 | +var robotSim = function(commands, obstacles) { |
| 36 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 37 | + const obstacleSet = new Set(obstacles.map(([x, y]) => `${x},${y}`)); |
| 38 | + |
| 39 | + let x = 0; |
| 40 | + let y = 0; |
| 41 | + let directionIndex = 0; |
| 42 | + let result = 0; |
| 43 | + |
| 44 | + for (const command of commands) { |
| 45 | + if (command === -1) { |
| 46 | + directionIndex = (directionIndex + 1) % 4; |
| 47 | + } else if (command === -2) { |
| 48 | + directionIndex = (directionIndex + 3) % 4; |
| 49 | + } else { |
| 50 | + const [dx, dy] = directions[directionIndex]; |
| 51 | + for (let step = 0; step < command; step++) { |
| 52 | + const nextX = x + dx; |
| 53 | + const nextY = y + dy; |
| 54 | + if (obstacleSet.has(`${nextX},${nextY}`)) break; |
| 55 | + x = nextX; |
| 56 | + y = nextY; |
| 57 | + result = Math.max(result, x * x + y * y); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return result; |
| 63 | +}; |
0 commit comments