1
/**
2
* @param {number[]} commands
3
* @param {number[][]} obstacles
4
* @return {number}
5
*/
6
var robotSim = function (commands, obstacles) {
7
let result = 0;
8
let currentPosition = [0, 0];
9
let currentDirection = "top";
10
const mySet = new Set();
11

12
// This is to have a O(1) check instead of doing a linear scan
13
obstacles.forEach((obs) => {
14
mySet.add(`${obs[0]},${obs[1]}`);
15
}); // O(m)
16

17
for (let i = 0; i < commands.length; i++) {
18
// O(n)
19
const move = commands[i];
20
if (move === -1) {
21
if (currentDirection === "top") {
22
currentDirection = "right";
23
} else if (currentDirection === "right") {
24
currentDirection = "down";
25
} else if (currentDirection === "down") {
26
currentDirection = "left";
27
} else {
28
currentDirection = "top";
29
}
30
}
31

32
if (move === -2) {
33
if (currentDirection === "top") {
34
currentDirection = "left";
35
} else if (currentDirection === "left") {
36
currentDirection = "down";
37
} else if (currentDirection === "down") {
38
currentDirection = "right";
39
} else {
40
currentDirection = "top";
41
}
42
}
43

44
if (move > 0) {
45
for (let i = 0; i < move; i++) {
46
O(move);
47
const isY = currentDirection === "top" || currentDirection === "down";
48
const isPositive =
49
currentDirection === "top" || currentDirection === "right";
50

51
const newPosition = [
52
currentPosition[0] + (!isY ? (isPositive ? 1 : -1) : 0),
53
currentPosition[1] + (isY ? (isPositive ? 1 : -1) : 0),
54
];
55
const positionString = `${newPosition[0]},${newPosition[1]}`;
56

57
if (!mySet.has(positionString)) {
58
currentPosition = newPosition;
59
result = Math.max(
60
result,
61
Math.pow(currentPosition[0], 2) + Math.pow(currentPosition[1], 2)
62
);
63
} else {
64
break;
65
}
66
}
67
}
68
}
69
return result;
70
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0