Skip to content

Commit 9c0f202

Browse files
authored
Create Hamiltonian Cycle
1 parent 93097a5 commit 9c0f202

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
#define V 5
6+
7+
void printSolution(int path[]);
8+
9+
bool isSafe(int v, bool graph[V][V],
10+
int path[], int pos)
11+
{
12+
13+
if (graph [path[pos - 1]][ v ] == 0)
14+
return false;
15+
16+
for (int i = 0; i < pos; i++)
17+
if (path[i] == v)
18+
return false;
19+
20+
return true;
21+
}
22+
23+
24+
bool hamCycleUtil(bool graph[V][V],
25+
int path[], int pos)
26+
{
27+
28+
if (pos == V)
29+
{
30+
31+
if (graph[path[pos - 1]][path[0]] == 1)
32+
return true;
33+
else
34+
return false;
35+
}
36+
37+
38+
for (int v = 1; v < V; v++)
39+
{
40+
// to Hamiltonian Cycle */
41+
if (isSafe(v, graph, path, pos))
42+
{
43+
path[pos] = v;
44+
45+
/* recur to construct rest of the path */
46+
if (hamCycleUtil (graph, path, pos + 1) == true)
47+
return true;
48+
49+
/* If adding vertex v doesn't lead to a solution,
50+
then remove it */
51+
path[pos] = -1;
52+
}
53+
}
54+
55+
/* If no vertex can be added to
56+
Hamiltonian Cycle constructed so far,
57+
then return false */
58+
return false;
59+
}
60+
61+
62+
bool hamCycle(bool graph[V][V])
63+
{
64+
int *path = new int[V];
65+
for (int i = 0; i < V; i++)
66+
path[i] = -1;
67+
68+
69+
path[0] = 0;
70+
if (hamCycleUtil(graph, path, 1) == false )
71+
{
72+
cout << "\nSolution does not exist";
73+
return false;
74+
}
75+
76+
printSolution(path);
77+
return true;
78+
}
79+
80+
81+
void printSolution(int path[])
82+
{
83+
cout << "Solution Exists:"
84+
" Following is one Hamiltonian Cycle \n";
85+
for (int i = 0; i < V; i++)
86+
cout << path[i] << " ";
87+
88+
cout << path[0] << " ";
89+
cout << endl;
90+
}
91+
92+
int main()
93+
{
94+
95+
bool graph1[V][V] = {{0, 1, 0, 1, 0},
96+
{1, 0, 1, 1, 1},
97+
{0, 1, 0, 0, 1},
98+
{1, 1, 0, 0, 1},
99+
{0, 1, 1, 1, 0}};
100+
101+
hamCycle(graph1);
102+
103+
104+
bool graph2[V][V] = {{0, 1, 0, 1, 0},
105+
{1, 0, 1, 1, 1},
106+
{0, 1, 0, 0, 1},
107+
{1, 1, 0, 0, 0},
108+
{0, 1, 1, 0, 0}};
109+
110+
111+
hamCycle(graph2);
112+
113+
return 0;
114+
}

0 commit comments

Comments
 (0)