Home  >  Article  >  Backend Development  >  Peterson diagram problem in C program

Peterson diagram problem in C program

PHPz
PHPzforward
2023-08-26 11:01:10871browse

Suppose we have a graph as shown below. This graph is a Peterson diagram. Vertices are numbered from 0 to 9. Each vertex has some letters. Consider a walk W on this graph using L vertices. When the letter sequence in walking W is the same as S, the string S is realized by walking W. We can visit a vertex multiple times.

Peterson diagram problem in C program

For example, a string S is similar to "ABBECCD", which is implemented by walking (0, 1, 6, 9, 7, 2, 3). Our task is to find such a walk and, if such a walk exists, find the lexicographically smallest walk. If there is no such walk, -1 is returned.

Algorithm

petersonGraphWalk(S, v) -The Chinese translation of

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

Example

is:

Example

#include<iostream>
using namespace std;
bool adj_mat[10][10] = {{0, 1, 0, 0, 1, 1, 0, 0, 0, 0},
   {1, 0, 1, 0, 0, 0, 1, 0, 0, 0},
   {0, 1, 0, 1, 0, 0, 0, 1, 0, 0},
   {0, 0, 1, 0, 1, 0, 0, 0, 1, 0},
   {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},
   {1, 0, 0, 0, 0, 0, 0, 1, 1, 0},
   {0, 1, 0, 0, 0, 0, 0, 0, 1, 1},
   {0, 0, 1, 0, 0, 1, 0, 0, 0, 1},
   {0, 0, 0, 1, 0, 1, 1, 0, 0, 0},
   {0, 0, 0, 0, 1, 0, 1, 1, 0, 0}
};
char S[100005];
char res[100005];
bool petersonGraphWalk(char* S, int v){
   res[0] = v + &#39;0&#39;;
   for(int i = 1; S[i]; i++){
      //traverse the outer graph
      if(adj_mat[v][S[i] - &#39;A&#39;] || adj_mat[S[i] - &#39;A&#39;][v]){
         v = S[i] - &#39;A&#39;;
      }
      //then check the inner graph
      else if(adj_mat[v][S[i] - &#39;A&#39; + 5] || adj_mat[S[i] - &#39;A&#39; + 5][v]){
         v = S[i] - &#39;A&#39; + 5;
      }else{
         return false;
      }
      res[i] = v + &#39;0&#39;;
   }
   return true;
}
main() {
   char* str = "ABBECCD";
   if(petersonGraphWalk(str, str[0] - &#39;A&#39;) || petersonGraphWalk(str, str[0] - &#39;A&#39; + 5)){
      cout << res;
   }else{
      cout << -1;
   }
}

Output

0169723

The above is the detailed content of Peterson diagram problem in C program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete