-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathhamiltonian.cpp
More file actions
71 lines (71 loc) · 1.64 KB
/
hamiltonian.cpp
File metadata and controls
71 lines (71 loc) · 1.64 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
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
int total = 0;
struct Edge
{
int src, dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> const &edges, int n)
{
adjList.resize(n);
for (Edge edge : edges)
{
int src = edge.src;
int dest = edge.dest;
adjList[src].push_back(dest);
adjList[dest].push_back(src);}
}
};
void printPath(vector<int> const &path)
{
for (int i : path)
{
cout << i << ' ';
}
cout << endl;
}
void findhamiltonianPaths(Graph const &graph, int v, vector<bool> &visited,
vector<int> &path, int n)
{
if (path.size() == n)
{
total++;
printPath(path);
return;
}
for (int w : graph.adjList[v])
{
if (!visited[w])
{
visited[w] = true;
path.push_back(w);
findhamiltonianPaths(graph, w, visited, path, n);
visited[w] = false;
path.pop_back();}
}
}
void findfindhamiltonianPaths(Graph const &graph, int n)
{
for (int start = 0; start < n; start++)
{
vector<int> path;
path.push_back(start);
vector<bool> visited(n);
visited[start] = true;
findhamiltonianPaths(graph, start, visited, path, n);
}
}
int main()
{
vector<Edge> edges = {
{0, 1}, {0, 2}, {0, 3}, {2, 1}, {1, 2}, {3, 2}};
int n = 4;
Graph graph(edges, n);
findfindhamiltonianPaths(graph, n);
cout << "Total number of Hamiltonian cycles:- " << total << endl;
return 0;
}