math
]
Leetcode 1041. Robot Bounded In Circle
https://leetcode.com/problems/robot-bounded-in-circle
Let dx, dy
be directions of our robot and x,y
be its coordinates. Then using linear algepra we can say that if we rotate to the left, then dx, dy = -dy, dx
, similar if we rotate to the right. So, now we can easily follow the place of our robot. How to understand if his path will be bounded by some circle? We need to understand if he is going to loop. There are 3
possible options where path will be bounded.
- In the end it will arrive to the starting position.
- It will not arrive to the starting position and his orientation is rotated to the left or to the right. Then it can be shown easily that after
4
loops robot will return to the original place. - It will not arrive to the start and his orientation is opposite, then after
2
loops he will arrive at the starting place.
So, let us just check that after 4
times we traverse our instructions
robot will be at the start, that is all!
Complexity: Time complexity is O(4n)
, space complexity is O(1)
.
class Solution:
def isRobotBounded(self, instructions):
dx, dy, x, y = 0, 1, 0, 0
for l in 4*instructions:
if l == "G":
x, y = x+dx, y+dy
elif l == "L":
dx, dy = -dy, dx
else:
dx, dy = dy, -dx
return (x,y) == (0,0)
PS I realized that we do not really need to traverse instructions
4 times, we can just return (x,y) == 0 or (dx, dy) != (0,1)
, but this solution was already provided by others, so I left my solution as it is.
If you like the solution, you can upvote it on leetcode discussion section: Problem 1041