Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check whether given sequence of moves is circular upon infinite repetition

  • Last Updated : 01 Feb, 2022

Given a string str denoting a sequence of moves. The task is to check if the moves are repeated an infinite number of times then the movements will be bound in a circular path or not. The movements can be of following types:

  • “G”: go straight 1 unit;
  • “L”: turn 90 degrees to the left;
  • “R”: turn 90 degrees to the right.

Examples:

Input: str = “GGLLGG”
Output: true
Explanation: The movements are: (0, 0) to (0, 2); turn 180 degrees; and then returns to (0, 0).
When repeating these instructions, the movements are bounded in a circular path.

Input: str = “GG”
Output: false
Explanation: The moves will go infinitely in forward direction only.

Input: str = “GL”
Output: true
Explanation: The moves upon infinite repetition are
from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> . . .
Thus bounded in this circular path.

 

Approach: At any move, one can face at any of the four directions, “North”, “South”, “East” and “West”. The idea is to consider initially standing at (0, 0) position and facing North. As the instruction is given infinite number of times, the movements will lead to a circular path if after some instructions it returns back to the starting point.

This is possible only if after one instruction its direction is changed or it returns to the origin.

               N

              |

              |

 W ————– E

              |

              |

              S 

To figure out the position and direction of the robot after every instruction, add or subtract certain values from its position depending on the direction.

This is what the direction and movement will be for each direction looks like: 

DirectionAddLR
North(0, 1)WestEast
West(-1, 0)SouthNorth
East(1, 0)NorthSouth
South(0, -1)EastWest

Follow the steps mentioned below.

  • Store the directions in the form of a vector. Since the initial position is at (0, 0), the direction are taken in the anti-clockwise direction to calculate the next position. So, the vector is {N, W, S, E}.
  • Initialize i to 0 to keep track of the rotation. Here, 0 represents the initial direction. If it is 0 at the end of execution, and the position is not the starting position, the function will return false.
  • Initialize x and y to 0 as its initial position is (0, 0).
  • Run a loop to iterate through the instructions one by one.
  • Check for right or left rotation. Increment i by 1 for left and by 3 for right rotation. (3 for right because one right rotation is equal to 3 left rotation and here directions are considered anti-clockwise)
  • If it goes straight, add the values of x and y from the vector corresponding to ith direction.
  • End Loop.
  • Check if the movements lead back to starting position or the direction is anything other than the starting direction. If any of these two conditions is true, return true. Otherwise, return false.

Below is the implementation of the above approach.

C++




// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the movements
// are repeated infinite times then
// it will be bounded in circular path or not
void isRobotBounded(string str)
{
    vector<vector<int> > dir
        = { { 0, 1 }, { -1, 0 }, { 0, -1 }, { 1, 0 } };
    int i = 0;
    int x = 0;
    int y = 0;
 
    for (int s = 0; s < str.size(); s++) {
        if (str.at(s) == 'L') {
            i = (i + 1) % 4;
        }
        else if (str.at(s) == 'R') {
            i = (i + 3) % 4;
        }
        else {
            x = x + dir[i][0];
            y = y + dir[i][1];
        }
    }
    if (x == 0 && y == 0 || i != 0)
        cout << "true";
    else
        cout << "false";
}
 
// Driver code
int main()
{
    string str = "GGLLGG";
 
    isRobotBounded(str);
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to check if the movements
  // are repeated infinite times then
  // it will be bounded in circular path or not
  static void isRobotBounded(String str)
  {
    int[][] dir
      = { { 0, 1 }, { -1, 0 }, { 0, -1 }, { 1, 0 } };
    int i = 0;
    int x = 0;
    int y = 0;
 
    for (int s = 0; s < str.length(); s++) {
      if (str.charAt(s) == 'L') {
        i = (i + 1) % 4;
      }
      else if (str.charAt(s) == 'R') {
        i = (i + 3) % 4;
      }
      else {
        x = x + dir[i][0];
        y = y + dir[i][1];
      }
    }
    if (x == 0 && y == 0 || i != 0)
      System.out.println("true");
    else
      System.out.println("false");
  }
 
  // Driver code
  public static void main (String[] args) {
    String str = "GGLLGG";
 
    isRobotBounded(str);
 
  }
}
 
 
// This code is contributed by hrithikgarg03188.

Python3




# Python code for the above approach
 
# Function to check if the movements
# are repeated infinite times then
# it will be bounded in circular path or not
def isRobotBounded(str):
    dir = [[0, 1], [-1, 0], [0, -1], [1, 0]]
    i = 0
    x = 0
    y = 0
 
    for s in range(len(str)):
        if (str[s] == 'L'):
            i = (i + 1) % 4
        elif(str[s] == 'R'):
            i = (i + 3) % 4
        else:
            x = x + dir[i][0]
            y = y + dir[i][1]
    if (x == 0 and y == 0 or i != 0):
        print("true")
    else:
        print("false")
 
# Driver code
str = "GGLLGG"
isRobotBounded(str)
 
# This code is contributed by Saurabh Jaiswal

C#




// C# code to implement above approach
using System;
class GFG
{
 
  // Function to check if the movements
  // are repeated infinite times then
  // it will be bounded in circular path or not
  static void isRobotBounded(string str)
  {
    int [,]dir
      = { { 0, 1 }, { -1, 0 }, { 0, -1 }, { 1, 0 } };
    int i = 0;
    int x = 0;
    int y = 0;
 
    for (int s = 0; s < str.Length; s++) {
      if (str[s] == 'L') {
        i = (i + 1) % 4;
      }
      else if (str[s] == 'R') {
        i = (i + 3) % 4;
      }
      else {
        x = x + dir[i, 0];
        y = y + dir[i, 1];
      }
    }
    if (x == 0 && y == 0 || i != 0)
      Console.Write("true");
    else
      Console.Write("false");
  }
 
  // Driver code
  public static void Main()
  {
    string str = "GGLLGG";
 
    isRobotBounded(str);
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
        // JavaScript code for the above approach
 
        // Function to check if the movements
        // are repeated infinite times then
        // it will be bounded in circular path or not
        function isRobotBounded(str)
        {
            let dir
                = [[0, 1], [-1, 0], [0, -1], [1, 0]];
            let i = 0;
            let x = 0;
            let y = 0;
 
            for (let s = 0; s < str.length; s++) {
                if (str[s] == 'L') {
                    i = (i + 1) % 4;
                }
                else if (str[s] == 'R') {
                    i = (i + 3) % 4;
                }
                else {
                    x = x + dir[i][0];
                    y = y + dir[i][1];
                }
            }
            if (x == 0 && y == 0 || i != 0)
                document.write("true")
            else
                document.write("false")
        }
 
        // Driver code
        let str = "GGLLGG";
        isRobotBounded(str);
 
         // This code is contributed by Potta Lokesh
    </script>

 
 

Output
true

 

Time Complexity: O(N) where N is the length of the string
Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!