Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 one 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

We strongly recommend that you click here and practice it, before moving on to the solution.

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. 

  1. If current direction is North, then ‘G’ increments y and doesn’t change x. 
  2. If current direction is East, then ‘G’ increments x and doesn’t change y. 
  3. If current direction is South, then ‘G’ decrements y and doesn’t change x. 
  4. 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. 

  1. If current direction is North, then ‘L’ changes direction to West and ‘R’ changes to East 
  2. If current direction is East, then ‘L’ changes direction to North and ‘R’ changes to South 
  3. If current direction is South, then ‘L’ changes direction to East and ‘R’ changes to West 
  4. If current direction is West, then ‘L’ changes direction to South and ‘R’ changes to North.

Below is the implementation of above idea :

C++




// 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 false
bool 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 program
int main()
{
    char path[] = "GLGLGLG";
    if (isCircular(path))
      cout << "Given sequence of moves is circular";
    else
      cout << "Given sequence of moves is NOT circular";
}


Java




// Write Java code here
// A Java program to check if
// the given path for a robot
// is circular or not
class GFG {
  
// Macros for East, North, South and West
 
// This function returns true if
// the given path is circular,
// else false
static 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 program
public 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




# Python program to check if the given path for a robot is circular
# or not
N = 0
E = 1
S = 2
W = 3
 
# This function returns true if the given path is circular,
# else false
def 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 program
path = "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


C#




// A C# program to check if
// the given path for a robot
// is circular or not
using System;
 
class GFG {
 
// Macros for East, North, South and West
 
// This function returns true if
// the given path is circular,
// else false
static bool isCircular(string 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
    // 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);
}
 
// Driver Code
public 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


Javascript




<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. 
Auxiliary Space:  O(1)

Approach 2: Using a Hash Map
In this approach, we can maintain a hash map to store the count of the number of times the robot has visited a particular position. We can start from the initial position (0,0) and then update the position of the robot based on the moves given in the sequence. After completing the sequence, if the robot returns to the initial position and has not visited any other position more than once, then we can say that the sequence is circular.

In this approach, we maintain the current position and direction of the robot using two variables x and y and dir, respectively. We also maintain a hash map freq to store the frequency of each direction encountered in the path so far. For each character in the path, we update the position and direction of the robot and increment the frequency of the current direction in the hash map. After processing each move, we check if the robot has returned to the initial position and direction. If so, and if the frequency of each direction encountered so far is equal, then we conclude that the sequence of moves is circular. Otherwise, we continue processing the remaining moves.

C++




#include <bits/stdc++.h>
using namespace std;
 
bool isCircular(char* path) {
    int x = 0, y = 0; // Initial position of robot
    int dir = 0; // Initial direction of robot (North)
 
    // Hash map to store the frequency of each direction
    unordered_map<char, int> freq;
    freq['N'] = freq['E'] = freq['S'] = freq['W'] = 0;
 
    // Traverse through each character in the path
    for (int i = 0; path[i] != '\0'; i++) {
        if (path[i] == 'N') {
            y++;
            dir = 0;
        } else if (path[i] == 'E') {
            x++;
            dir = 1;
        } else if (path[i] == 'S') {
            y--;
            dir = 2;
        } else if (path[i] == 'W') {
            x--;
            dir = 3;
        }
 
        // Increment the frequency of the current direction
        freq[path[i]]++;
 
        // If the robot returns to the initial position and direction after
        // processing the current move, then the sequence of moves is circular
        if (x == 0 && y == 0 && dir == 0 && freq['N'] == freq['S'] && freq['E'] == freq['W']) {
            return true;
        }
    }
 
    // If the robot does not return to the initial position and direction
    // after processing all the moves, then the sequence of moves is not circular
    return false;
}
 
// Driver code
int main() {
    char path[] = "GLGLGLG"; // Sample input
    if (isCircular(path)) {
        cout << "The given sequence of moves is circular";
    } else {
        cout << "The given sequence of moves is not circular";
    }
    return 0;
}


Java




import java.util.HashMap;
 
public class Main {
    static boolean isCircular(char[] path) {
        int x = 0, y = 0; // Initial position of robot
        int dir = 0; // Initial direction of robot (North)
 
        // Hash map to store the frequency of each direction
        HashMap<Character, Integer> freq = new HashMap<>();
        freq.put('N', 0);
        freq.put('E', 0);
        freq.put('S', 0);
        freq.put('W', 0);
 
        // Traverse through each character in the path
        for (char c : path) {
            if (c == 'N') {
                y++;
                dir = 0;
            } else if (c == 'E') {
                x++;
                dir = 1;
            } else if (c == 'S') {
                y--;
                dir = 2;
            } else if (c == 'W') {
                x--;
                dir = 3;
            }
 
            // Increment the frequency of the current direction
            if(c == 'N' || c == 'S' || c == 'W' || c == 'E')
                freq.put(c, freq.get(c) + 1);
 
            // If the robot returns to the initial position and direction after
            // processing the current move, then the sequence of moves is circular
            if (x == 0 && y == 0 && dir == 0 &&
                freq.get('N') == freq.get('S') &&
                freq.get('E') == freq.get('W')) {
                return true;
            }
        }
 
        // If the robot does not return to the initial position and direction
        // after processing all the moves, then the sequence of moves is not circular
        return false;
    }
 
    // Driver code
    public static void main(String[] args) {
        char[] path = "GLGLGLG".toCharArray(); // Sample input
        if (isCircular(path)) {
            System.out.println("The given sequence of moves is circular");
        } else {
            System.out.println("The given sequence of moves is not circular");
        }
    }
}


Python3




def isCircular(path):
    x, y = 0, 0  # Initial position of robot
    dir = 0  # Initial direction of robot (North)
 
    # Dictionary to store the frequency of each direction
    freq = {
        'N': 0,
        'E': 0,
        'S': 0,
        'W': 0
    }
 
    # Traverse through each character in the path
    for c in path:
        if c == 'N':
            y += 1
            dir = 0
        elif c == 'E':
            x += 1
            dir = 1
        elif c == 'S':
            y -= 1
            dir = 2
        elif c == 'W':
            x -= 1
            dir = 3
         
 
        # Increment the frequency of the current direction
        try:
            freq += 1
        except:
            pass
 
        # If the robot returns to the initial position and direction after
        # processing the current move, then the sequence of moves is circular
        if x == 0 and y == 0 and dir == 0 and freq['N'] == freq['S'] and freq['E'] == freq['W']:
            return True
 
    # If the robot does not return to the initial position and direction
    # after processing all the moves, then the sequence of moves is not circular
    return False
 
# Driver code
path = "GLGLGLG"  # Sample input
if isCircular(path):
    print("The given sequence of moves is circular")
else:
    print("The given sequence of moves is not circular")


C#




using System;
using System.Collections.Generic;
 
class Program {
    static bool IsCircular(char[] path) {
        int x = 0, y = 0; // Initial position of robot
        int dir = 0; // Initial direction of robot (North)
 
        // Dictionary to store the frequency of each direction
        Dictionary<char, int> freq = new Dictionary<char, int> {
            { 'N', 0 },
            { 'E', 0 },
            { 'S', 0 },
            { 'W', 0 }
        };
 
        // Traverse through each character in the path
        foreach (char c in path) {
            if (c == 'N') {
                y++;
                dir = 0;
            } else if (c == 'E') {
                x++;
                dir = 1;
            } else if (c == 'S') {
                y--;
                dir = 2;
            } else if (c == 'W') {
                x--;
                dir = 3;
            }
 
            // Increment the frequency of the current direction
            if(c == 'N' || c == 'S' || c == 'W' || c == 'E')
            freq++;
 
            // If the robot returns to the initial position and direction after
            // processing the current move, then the sequence of moves is circular
            if (x == 0 && y == 0 && dir == 0 &&
                freq['N'] == freq['S'] &&
                freq['E'] == freq['W']) {
                return true;
            }
        }
 
        // If the robot does not return to the initial position and direction
        // after processing all the moves, then the sequence of moves is not circular
        return false;
    }
 
    // Driver code
    static void Main(string[] args) {
        char[] path = "GLGLGLG".ToCharArray(); // Sample input
        if (IsCircular(path)) {
            Console.WriteLine("The given sequence of moves is circular");
        } else {
            Console.WriteLine("The given sequence of moves is not circular");
        }
    }
}


Javascript




function isCircular(path) {
    let x = 0, y = 0; // Initial position of robot
    let dir = 0; // Initial direction of robot (North)
 
    // Object to store the frequency of each direction
    const freq = { 'N': 0, 'E': 0, 'S': 0, 'W': 0 };
 
    // Traverse through each character in the path
    for (let i = 0; i < path.length; i++) {
        const c = path[i];
        if (c === 'N') {
            y++;
            dir = 0;
        } else if (c === 'E') {
            x++;
            dir = 1;
        } else if (c === 'S') {
            y--;
            dir = 2;
        } else if (c === 'W') {
            x--;
            dir = 3;
        }
 
        // Increment the frequency of the current direction
        freq++;
 
        // If the robot returns to the initial position and direction after
        // processing the current move, then the sequence of moves is circular
        if (x === 0 && y === 0 && dir === 0 && freq['N'] === freq['S'] &&
            freq['E'] === freq['W']) {
            return true;
        }
    }
 
    // If the robot does not return to the initial position and direction
    // after processing all the moves, then the sequence of moves is not circular
    return false;
}
 
// Driver code
const path = ['G', 'L', 'G', 'L', 'G', 'L', 'G']; // Sample input
if (isCircular(path)) {
    console.log("The given sequence of moves is circular");
} else {
    console.log("The given sequence of moves is not circular");
}


Output

The given sequence of moves is circular




Time Complexity: O(n) where n is the number of moves in the given sequence. 
Auxiliary Space:  O(n)



Last Updated : 19 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads