题目地址:https://leetcode-cn.com/problems/walking-robot-simulation/description/
var robotSim = function (commands, obstacles) {
let obstacle = {}, x = 0, y = 0, res = 0;
let direction = 0; //0 = north, 1 = east, 2 = south, 3 = west
for (let i = 0; i < obstacles.length; i++) {
obstacle[obstacles[i]] = true;
}
for (let i = 0; i < commands.length; i++) {
if (commands[i] == -1) {
direction = (direction + 1) % 4; // updated
} else if (commands[i] == -2) {
direction = (direction - 1 + 4) % 4;
} else {
while (commands[i]--) {
let previousX = x, previousY = y;
if (direction === 0) y++;
if (direction === 1) x++;
if (direction === 2) y--;
if (direction === 3) x--;
if (obstacle[x + "," + y]) {
[x, y] = [previousX, previousY];
break;
}
}
}
res = Math.max(res, x ** 2 + y ** 2);
}
return res;
};