-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPetersonGraph.cpp
More file actions
65 lines (53 loc) · 1.19 KB
/
PetersonGraph.cpp
File metadata and controls
65 lines (53 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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;
}