forked from fineanmol/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Eulerian Path in undirected graph
82 lines (74 loc) · 1.74 KB
/
Eulerian Path in undirected graph
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <bits/stdc++.h>
using namespace std;
// Function to find out the path
// It takes the adjacency matrix
// representation of the graph as input
void findpath(int graph[][5], int n)
{
vector<int> numofadj;
// Find out number of edges each vertex has
for (int i = 0; i < n; i++)
numofadj.push_back(accumulate(graph[i],
graph[i] + 5, 0));
// Find out how many vertex has odd number edges
int startpoint = 0, numofodd = 0;
for (int i = n - 1; i >= 0; i--)
{
if (numofadj[i] % 2 == 1)
{
numofodd++;
startpoint = i;
}
}
// If number of vertex with odd number of edges
// is greater than two return "No Solution".
if (numofodd > 2)
{
cout << "No Solution" << endl;
return;
}
// If there is a path find the path
// Initialize empty stack and path
// take the starting current as discussed
stack<int> stack;
vector<int> path;
int cur = startpoint;
// Loop will run until there is element in the stack
// or current edge has some neighbour.
while (!stack.empty() or
accumulate(graph[cur],
graph[cur] + 5, 0) != 0)
{
// If current node has not any neighbour
// add it to path and pop stack
// set new current to the popped element
if (accumulate(graph[cur],
graph[cur] + 5, 0) == 0)
{
path.push_back(cur);
cur = stack.top();
stack.pop();
}
// If the current vertex has at least one
// neighbour add the current vertex to stack,
// remove the edge between them and set the
// current to its neighbour.
else
{
for (int i = 0; i < n; i++)
{
if (graph[cur][i] == 1)
{
stack.push(cur);
graph[cur][i] = 0;
graph[i][cur] = 0;
cur = i;
break;
}
}
}
}
// print the path
for (auto ele : path) cout << ele << " -> ";
cout << cur << endl;
}