Open In App

A Peterson Graph Problem

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The following graph G is called a Petersen graph and its vertices have been numbered from 0 to 9. Some letters have also been assigned to vertices of G, as can be seen from the following picture: 

Let’s consider a walk W in graph G, which consists of L vertices W1, W2, …, WL. A string S of L letters ‘A’ – ‘E’ is realized by walking W if the sequence of letters written along W is equal to S. Vertices can be visited multiple times while walking along W.

For example, S = ‘ABBECCD’ is realized by W = (0, 1, 6, 9, 7, 2, 3). Determine whether there is a walk W that realizes a given string S in graph G and if so then find the lexicographically least such walk. The only line of input contains one string S. If there is no walk W which realizes S, then output -1 otherwise, you should output the least lexicographical walk W which realizes S. 
 

Example of a Petersen Graph

Example of a Petersen Graph

Examples: 

Input : s = 'ABB'
Output: 016
Explanation: As we can see in the graph
             the path from ABB is 016.
Input : s = 'AABE'
Output :-1
Explanation: As there is no path that
             exists, hence output is -1.

Algorithm for a Peterson Graph Problem:

petersonGraphWalk(S, v):

begin
    res := starting vertex
    for each character c in S except the first one, do
        if there is an edge between v and c in outer graph, then      
            v := c
        else if there is an edge between v and c+5 in inner graph, then
            v := c + 5
        else
            return false
        end if
            put v into res
        done
    return true
end

Below is the implementation of the above algorithm:

C++




// C++ program to find the
// path in Peterson graph
#include <bits/stdc++.h>
using namespace std;
 
// path to be checked
char S[100005];
 
// adjacency matrix.
bool adj[10][10];
 
// resulted path - way
char result[100005];
 
// we are applying breadth first search
// here
bool findthepath(char* S, int v)
{
    result[0] = v + '0';
    for (int i = 1; S[i]; i++) {
         
        // first traverse the outer graph
        if (adj[v][S[i] - 'A'] || adj[S[i] -
                              'A'][v]) {
            v = S[i] - 'A';
        }
 
        // then traverse the inner graph
        else if (adj[v][S[i] - 'A' + 5] ||
                 adj[S[i] - 'A' + 5][v]) {
            v = S[i] - 'A' + 5;
        }
 
        // if the condition failed to satisfy
        // return false
        else
            return false;
 
        result[i] = v + '0';
    }
 
    return true;
}
 
// driver code
int main()
{
    // here we have used adjacency matrix to make
    // connections between the connected nodes
    adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] =
    adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] =
    adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] =
    adj[9][6] = adj[6][8] = adj[8][5] = true;
     
    // path to be checked
    char S[] = "ABB";
     
    if (findthepath(S, S[0] - 'A') ||
        findthepath(S, S[0] - 'A' + 5)) {
        cout << result;
    } else {
        cout << "-1";
    }
    return 0;
}


Java




// Java program to find the
// path in Peterson graph
class GFG
{
 
    // path to be checked
    static char []S = new char[100005];
 
    // adjacency matrix.
    static boolean [][]adj = new boolean[10][10];
     
    // resulted path - way
    static char[] result = new char[100005];
     
    // we are applying breadth first search
    // here
    static boolean findthepath(char[] S, int v)
    {
        result[0] = (char) (v + '0');
        for (int i = 1; i<(int)S.length; i++)
        {
             
            // first traverse the outer graph
            if (adj[v][S[i] - 'A'] ||
                adj[S[i] - 'A'][v])
            {
                v = S[i] - 'A';
            }
     
            // then traverse the inner graph
            else if (adj[v][S[i] - 'A' + 5] ||
                    adj[S[i] - 'A' + 5][v])
            {
                v = S[i] - 'A' + 5;
            }
     
            // if the condition failed to satisfy
            // return false
            else
                return false;
     
            result[i] = (char) (v + '0');
        }
        return true;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        // here we have used adjacency matrix to make
        // connections between the connected nodes
        adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] =
        adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] =
        adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] =
        adj[9][6] = adj[6][8] = adj[8][5] = true;
         
        // path to be checked
        char S[] = "ABB".toCharArray();
         
        if (findthepath(S, S[0] - 'A') ||
            findthepath(S, S[0] - 'A' + 5))
        {
            System.out.print(result);
        }
        else
        {
            System.out.print("-1");
        }
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to find the
# path in Peterson graph
# path to be checked
 
# adjacency matrix.
adj = [[False for i in range(10)] for j in range(10)]
 
# resulted path - way
result = [0]
 
# we are applying breadth first search
# here
def findthepath(S, v):
    result[0] = v
    for i in range(1, len(S)):
         
        # first traverse the outer graph
        if (adj[v][ord(S[i]) - ord('A')] or
            adj[ord(S[i]) - ord('A')][v]):
            v = ord(S[i]) - ord('A')
             
        # then traverse the inner graph
        else if (adj[v][ord(S[i]) - ord('A') + 5] or
               adj[ord(S[i]) - ord('A') + 5][v]):
            v = ord(S[i]) - ord('A') + 5
         
        # if the condition failed to satisfy
        # return false
        else:
            return False
         
        result.append(v)
         
    return True
 
# driver code
# here we have used adjacency matrix to make
# connections between the connected nodes
adj[0][1] = adj[1][2] = adj[2][3] = \
adj[3][4] = adj[4][0] = adj[0][5] = \
adj[1][6] = adj[2][7] = adj[3][8] = \
adj[4][9] = adj[5][7] = adj[7][9] = \
adj[9][6] = adj[6][8] = adj[8][5] = True
 
# path to be checked
S= "ABB"
S=list(S)
if (findthepath(S, ord(S[0]) - ord('A')) or
    findthepath(S, ord(S[0]) - ord('A') + 5)):
    print(*result, sep = "")
else:
    print("-1")
     
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to find the
// path in Peterson graph
using System;
public class GFG
{
 
  // adjacency matrix.
  static bool [,]adj = new bool[10, 10];
 
  // resulted path - way
  static char[] result = new char[100005];
 
  // we are applying breadth first search
  // here
  static bool findthepath(String S, int v)
  {
    result[0] = (char) (v + '0');
    for (int i = 1; i < S.Length; i++)
    {
 
      // first traverse the outer graph
      if (adj[v,S[i] - 'A'] ||
          adj[S[i] - 'A',v])
      {
        v = S[i] - 'A';
      }
 
      // then traverse the inner graph
      else if (adj[v,S[i] - 'A' + 5] ||
               adj[S[i] - 'A' + 5,v])
      {
        v = S[i] - 'A' + 5;
      }
 
      // if the condition failed to satisfy
      // return false
      else
        return false;
 
      result[i] = (char) (v + '0');
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
 
    // here we have used adjacency matrix to make
    // connections between the connected nodes
    adj[0,1] = adj[1,2] = adj[2,3] = adj[3,4] =
      adj[4,0] = adj[0,5] = adj[1,6] = adj[2,7] =
      adj[3,8] = adj[4,9] = adj[5,7] = adj[7,9] =
      adj[9,6] = adj[6,8] = adj[8,5] = true;
 
    // path to be checked
    String S = "ABB";
    if (findthepath(S, S[0] - 'A') ||  findthepath(S, S[0] - 'A' + 5))
    {
      Console.WriteLine(result);
    }
    else
    {
      Console.Write("-1");
    }
  }
}
 
// This code is contributed by aashish1995


Javascript




<script>
 
// Javascript program to find the
// path in Peterson graph
 
// adjacency matrix.
let adj = new Array(10).fill(0).map(() => new Array(10).fill(false))
 
// resulted path - way
let result = new Array(100005)
 
// we are applying breadth first search
// here
function findthepath(S, v) {
  result[0] = v
  for (let i = 1; i < S.length; i++) {
 
    // first traverse the outer graph
    if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0)] ||
      adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0)][v]) {
      v = S[i].charCodeAt(0) - 'A'.charCodeAt(0);
    }
 
    // then traverse the inner graph
    else if (adj[v][S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5] ||
      adj[S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5][v]) {
      v = S[i].charCodeAt(0) - 'A'.charCodeAt(0) + 5;
    }
 
    // if the condition failed to satisfy
    // return false
    else
      return false;
 
    result[i] = String.fromCharCode(v + '0'.charCodeAt(0));
  }
  return true;
}
 
// Driver code
 
 
// here we have used adjacency matrix to make
// connections between the connected nodes
adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] =
  adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] =
  adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] =
  adj[9][6] = adj[6][8] = adj[8][5] = true;
 
// path to be checked
let S = "ABB";
S = S.split("")
if (findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0)) || findthepath(S, S[0].charCodeAt(0) - 'A'.charCodeAt(0) + 5)) {
  document.write(result.join(""));
}
else {
  document.write("-1");
}
 
 
// This code is contributed by Saurabh Jaiswal
 
</script>


Output

016

Time complexity: O(N)

The time complexity of the above program is O(N), where N is the length of the given string S. We are applying Breadth First Search here, which runs in linear time.

Space complexity: O(N)

The space complexity of the above program is O(N), where N is the length of the given string S. We are using two auxiliary arrays – result[] and S[] to store the path and the given string, respectively. Both of them require linear space.

 



Previous Article
Next Article

Similar Reads

What is Peterson Graph?
A graph is a data structure that is defined by two components : A node or a vertex.An edge E or ordered pair is a connection between two nodes u,v that is identified by a unique pair(u,v). The pair (u,v) is ordered because (u,v) is not the same as (v,u) in the case of a directed graph. The edge may have a weight or is set to one in case of an unwei
3 min read
Program to check for Peterson number
A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself. Example: Input : n = 145 Output = Yes Explanation: 145 = 5! + 4! + 1! = 120 + 24 +1 = 145 Input : n = 55 Output : No Explanation: 5! + 5! = 120 + 120 = 240 Since 55 is not equal to 240 It is not a Peterson number. We will pic
5 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorit
11 min read
Peterson's Algorithm in Process Synchronization
Prerequisite - Synchronization, Critical Section  The producer-consumer problem (or bounded buffer problem) describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue. Producers produce an item and put it into the buffer. If the buffer is already full then the producer will have to wait for an em
15+ min read
Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
Problem: Given 2 process i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. We strongly recommend to refer below basic solution discussed in previous article. Peterson's Algorithm for Mutual Exclusion | Set 1We would be resolving 2 issues in the previous algorithm.  Wast
11 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Article Tags :
Practice Tags :