Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 62c3958

Browse files
authoredJul 22, 2021
Create 874-walking-robot-simulation.js
1 parent 6d65568 commit 62c3958

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
 

‎874-walking-robot-simulation.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} commands
3+
* @param {number[][]} obstacles
4+
* @return {number}
5+
*/
6+
const robotSim = function(commands, obstacles) {
7+
const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]] // east, south, west, north
8+
const set = new Set()
9+
obstacles.forEach(([x, y]) => set.add(`${x},${y}`))
10+
let idx = 3, x = 0, y = 0, res = 0
11+
for(let e of commands) {
12+
if(e === -2) idx = (3 + idx) % 4
13+
else if(e === -1) idx = (1 + idx) % 4
14+
else {
15+
const [dx, dy] = dirs[idx]
16+
let dis = 0
17+
while(dis < e) {
18+
const nx = x + dx, ny = y + dy
19+
const k = `${nx},${ny}`
20+
if(set.has(k)) break
21+
x = nx
22+
y = ny
23+
dis++
24+
res = Math.max(res, x * x + y * y)
25+
}
26+
}
27+
}
28+
29+
return res
30+
};

0 commit comments

Comments
 (0)
Please sign in to comment.