Suppose we have a string s, that represents the moves of a robot. Robot is currently at (0, 0) position and it is facing north. The move string s may have these characters
- "F" to move forward direction, one unit
- "L" to rotate 90 degrees’ left
- "R" to rotate 90 degrees’ right
So if the robot repeatedly makes the moves in s in order, we have to check whether there is some box in the plane in which the robot never leaves or not.
So, if the input is like s = "FFRFRFFRF", then the output will be True, because robot moves 2 units towards north. then Then turns 90 right and move one block, then again rotate 90 degrees right and move 2 units south then again right, so this is forming a box.
To solve this, we will follow these steps −
- moves := an array that contains directions [[0, -1], [1, 0], [0, 1], [-1, 0]]
- r, c := 0, 0
- d := 0
- for times in range 0 to 3, do
- for i in range 0 to size of s, do
- if s[i] is same as "F", then
- (r, c) := (r + moves[d, 0], c + moves[d, 1])
- otherwise when s[i] is same as "L", then
- d :=(d + 3) mod 4
- otherwise when s[i] is same as "R", then
- d :=(d + 1) mod 4
- if s[i] is same as "F", then
- if r is same as 0 and c is same as 0, then
- return True
- for i in range 0 to size of s, do
- return False
Example
Let us see the following implementation to get better understanding −
def solve(s): moves = [[0, -1], [1, 0], [0, 1], [-1, 0]] r, c = 0, 0 d = 0 for times in range(4): for i in range(len(s)): if s[i] == "F": r, c = r + moves[d][0], c + moves[d][1] elif s[i] == "L": d = (d + 3) % 4 elif s[i] == "R": d = (d + 1) % 4 if r == 0 and c == 0: return True return False s = "FFRFRFFRF" print(solve(s))
Input
"FFRFRFFRF"
Output
True