Check if a given sequence of moves for a robot is circular or not - GeeksforGeeks

07 Jul, 2021
Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence of moves is circular if first and last positions of robot are same. A move can be on of the following. 
  G - Go one unit
  L - Turn left
  R - Turn right 
Examples: 
Input: path[] = "GLGLGLG"
Output: Given sequence of moves is circular 

Input: path[] = "GLLG"
Output: Given sequence of moves is circular 
 
The idea is to consider the starting position as (0, 0) and direction as East (We can pick any values for these). If after the given sequence of moves, we come back to (0, 0), then given sequence is circular, otherwise not. 
           N
           |
           |
   W -------------- E
           |
           |
           S 
The move ‘G’ changes either x or y according to following rules. a) If current direction is North, then ‘G’ increments y and doesn’t change x. b) If current direction is East, then ‘G’ increments x and doesn’t change y. c) If current direction is South, then ‘G’ decrements y and doesn’t change x. d) If current direction is West, then ‘G’ decrements x and doesn’t change y.The moves ‘L’ and ‘R’, do not change x and y coordinates, they only change direction according to following rule. a) If current direction is North, then ‘L’ changes direction to West and ‘R’ changes to East b) If current direction is East, then ‘L’ changes direction to North and ‘R’ changes to South c) If current direction is South, then ‘L’ changes direction to East and ‘R’ changes to West d) If current direction is West, then ‘L’ changes direction to South and ‘R’ changes to North.Below is the implementation of above idea : 
C++
Java
Python
C#
Javascript
// A c++ program to check if the given path for a robot is circular or not#include<iostream>using namespace std; // Macros for East, North, South and West#define N 0#define E 1#define S 2#define W 3 // This function returns true if the given path is circular, else falsebool isCircular(char path[]){  // Initialize starting point for robot as (0, 0) and starting  // direction as N North  int x = 0, y = 0;  int dir = N;   // Traverse the path given for robot  for (int i=0; path[i]; i++)  {      // Find current move      char move = path[i];       // If move is left or right, then change direction      if (move == 'R')        dir = (dir + 1)%4;      else if (move == 'L')        dir = (4 + dir - 1)%4;       // If move is Go, then change  x or y according to      // current direction      else // if (move == 'G')      {         if (dir == N)            y++;         else if (dir == E)            x++;         else if (dir == S)            y--;         else // dir == W            x--;      }  }    // If robot comes back to (0, 0), then path is cyclic  return (x == 0 && y == 0);} // Driver programint main(){    char path[] = "GLGLGLG";    if (isCircular(path))      cout << "Given sequence of moves is circular";    else      cout << "Given sequence of moves is NOT circular";}
// Write Java code here// A Java program to check if// the given path for a robot// is circular or notclass GFG {  // Macros for East, North, South and West // This function returns true if// the given path is circular,// else falsestatic boolean isCircular(char path[]){  // Initialize starting  // point for robot as  // (0, 0) and starting  // direction as N North  int x = 0, y = 0;  int dir = 0;    // Traverse the path given for robot  for (int i=0; i < path.length; i++)  {      // Find current move      char move = path[i];        // If move is left or      // right, then change direction      if (move == 'R')        dir = (dir + 1)%4;      else if (move == 'L')        dir = (4 + dir - 1) % 4;        // If move is Go, then      // change  x or y according to      // current direction      else // if (move == 'G')      {         if (dir == 0)            y++;         else if (dir == 1)            x++;         else if (dir == 2)            y--;         else // dir == 3            x--;      }  }     // If robot comes back to   // (0, 0), then path is cyclic  return (x == 0 && y == 0);}  // Driver programpublic static void main(String[] args){    String path_ = "GLGLGLG";    char path[] = path_.toCharArray();     if (isCircular(path))      System.out.println("Given sequence" +      " of moves is circular");    else      System.out.println("Given sequence" +      " of moves is NOT circular");}} // This code is contributed by prerna saini.
# Python program to check if the given path for a robot is circular# or notN = 0E = 1S = 2W = 3 # This function returns true if the given path is circular,# else falsedef isCircular(path):     # Initialize starting point for robot as (0, 0) and starting    # direction as N North    x = 0    y = 0    dir = N     # Traverse the path given for robot    for i in xrange(len(path)):         # Find current move        move = path[i]         # If move is left or right, then change direction        if move == 'R':            dir = (dir + 1)%4        elif move == 'L':            dir = (4 + dir - 1)%4         # If move is Go, then change x or y according to        # current direction        else:    # if move == 'G'            if dir == N:                y += 1            elif dir == E:                x += 1            elif dir == S:                y -= 1            else:                x -= 1     return (x == 0 and y == 0) # Driver programpath = "GLGLGLG"if isCircular(path):    print "Given sequence of moves is circular"else:    print "Given sequence of moves is NOT circular" # This code is contributed by BHAVYA JAIN
// A C# program to check if// the given path for a robot// is circular or notusing System; class GFG { // Macros for East, North, South and West // This function returns true if// the given path is circular,// else falsestatic bool isCircular(string path){     // Initialize starting// point for robot as// (0, 0) and starting// direction as N Northint x = 0, y = 0;int dir = 0; // Traverse the path// given for robotfor (int i = 0; i < path.Length; i++){         // Find current move    char move = path[i];     // If move is left or    // right, then change direction    if (move == 'R')        dir = (dir + 1) % 4;    else if (move == 'L')        dir = (4 + dir - 1) % 4;     // If move is Go, then    // change x or y according to    // current direction    // if (move == 'G')    else    {        if (dir == 0)            y++;        else if (dir == 1)            x++;        else if (dir == 2)            y--;        else // dir == 3            x--;    }} // If robot comes back to// (0, 0), then path is cyclicreturn (x == 0 && y == 0);} // Driver Codepublic static void Main(String[] args){    string path = "GLGLGLG";          if (isCircular(path))      Console.WriteLine("Given sequence of moves is circular");     else      Console.WriteLine("Given sequence of moves is NOT circular");}} // This code is contributed by Sam007
<script>    // A Javascript program to check if    // the given path for a robot    // is circular or not         // Macros for East, North, South and West       // This function returns true if    // the given path is circular,    // else false    function isCircular(path)    {         // Initialize starting        // point for robot as        // (0, 0) and starting        // direction as N North        let x = 0, y = 0;        let dir = 0;         // Traverse the path        // given for robot        for (let i = 0; i < path.length; i++)        {             // Find current move            let move = path[i];             // If move is left or            // right, then change direction            if (move == 'R')                dir = (dir + 1) % 4;            else if (move == 'L')                dir = (4 + dir - 1) % 4;             // If move is Go, then            // change x or y according to            // current direction            // if (move == 'G')            else            {                if (dir == 0)                    y++;                else if (dir == 1)                    x++;                else if (dir == 2)                    y--;                else // dir == 3                    x--;            }        }         // If robot comes back to        // (0, 0), then path is cyclic        return (x == 0 && y == 0);    }         let path = "GLGLGLG";           if (isCircular(path))      document.write("Given sequence of moves is circular");    else      document.write("Given sequence of moves is NOT circular");         // This code is contributed by decode2207.</script>
Output: 
Given sequence of moves is circular
Time Complexity: O(n) where n is number of moves in given sequence.  
YouTubeGeeksforGeeks502K subscribersCheck if a given sequence of moves for a robot is circular or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SKM3LenkDDc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed Kaustubh Deshmukh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
shubham_singh
decode2207
Amazon
Visa
Strings
Amazon
Visa
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Reverse words in a given string