[
simulation
]
Leetcode 0874 Walking Robot Simulation
Problem statement
https://leetcode.com/problems/walking-robot-simulation/
Solution
Just do what is asked, keep pl
is position of robot and dr
is direction of robot. On each step we either change direction or move.
Complexity
Time complexity is O(k + n)
, where k
is total number of steps of robot (one cell steps) and n
is number of obstacles. Space complexity is O(n)
.
Code
class Solution:
def robotSim(self, commands, obstacles):
pl, dr, ans = (0, 0), (0, 1), 0
obst_set = {(x, y) for x, y in obstacles}
for comm in commands:
if comm == -1:
dr = (dr[1], -dr[0])
elif comm == -2:
dr = (-dr[1], dr[0])
else:
for j in range(comm):
new_pl = (pl[0] + dr[0], pl[1] + dr[1])
if new_pl not in obst_set:
pl = new_pl
ans = max(ans, pl[0]**2 + pl[1]**2)
else:
break
return ans