Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- First part:
- Direction of robot at any point = [(count of L) - (count of R)]%4
- Every L is nullified by R. Thus only L-R matter
- Every 4 L nullify their effects
- Every 4 R nullify their effects resetting to initial direction
- Here the order of left and right does not matter, they can be separated by Gs and in any permutation.
- Also, 2 lefts = down and 3 lefts = right, and
- 2 rights = down and 3 rights = left
- 4 lefts = 4 rights = initial direction = up. This way the cycle restarts after 4 L or 4 R
- If initial direction is up
- Thus the final direction of n L moves depends on value of n%4 in this way:
- N%4 = 0 --> up
- = 1 --> left
- = 2 --> down
- = 3 --> right
- for n R moves it depends on (4-n%4)%4 in same way. This can ve verified
- Based on the current direction, the effect of G is decided(in +ve X, -ve X, +ve Y or -veY)
- Second part:
- 1. If final direction of robot is down then it will reach the starting point in second iteration.
- x, y --> x+a, y+b --> x, y (here x, y is origin a, b is resultant horizontal and vertical displacement in one cycle)
- 2. If final direction of robot is left or right it will reach the starting point in fourth iteration.
- [Just for proof]
- For left: x,y --> x-b, y+a --> x-b-a, y+a-b --> x-a, y-b --> x,y
- [If final direction is left in first cycle, it will be down in second, right in third and up in fourth)
- Same can be said for right
- 3. If a, b = 0, 0 then it will be always bounded
- 4. Only in case where a, b are non-zero and direction is up, it will be unbounded
- '''
- class Solution:
- def isRobotBounded(self, instructions: str) -> bool:
- direction = 0
- x, y = 0, 0
- mp = {0: (0,1), 1: (-1,0), 2: (0, -1), 3: (1, 0)}
- for i in instructions:
- if i == 'L':
- direction = (direction + 1)%4
- elif i == 'R':
- direction = (direction - 1)%4
- else:
- x += mp[direction][0]
- y += mp[direction][1]
- return (x==0 and y==0) or direction != 0
Add Comment
Please, Sign In to add comment