-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhamiltoniancycle.cpp
More file actions
60 lines (45 loc) · 1.18 KB
/
hamiltoniancycle.cpp
File metadata and controls
60 lines (45 loc) · 1.18 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
#include "hamiltoniancycle.h"
bool HamiltonianCycle::isSafe(int vertex, bool** Matrix, std::vector<int>& path, int position)
{
if(Matrix[ path[position-1] ][vertex] == 0)
return false;
for(int i=0; i<position; i++)
if(path[i]==vertex)
return false;
return true;
}
bool HamiltonianCycle::checkHamiltonianCycle(bool** Matrix, std::vector<int>& path, int position)
{
if(position == (int)path.size())
{
if(Matrix[ path[position-1] ][path[0]] == 1)
return true;
else
return false;
}
for(unsigned i=0; i<path.size(); i++)
{
if(HamiltonianCycle::isSafe((int)i, Matrix, path, position))
{
path[position] = (int)i;
if(HamiltonianCycle::checkHamiltonianCycle(Matrix, path, position+1) == true)
return true;
path[position] = -1;
}
}
return false;
}
std::vector<int> HamiltonianCycle::hamiltonianCycle(Graph* graph){
bool** Matrix = graph->getAdjacencyMatrix();
std::vector<int> path(graph->getVerticesNumber());
for(int i=0; i<graph->getVerticesNumber(); i++){
path[i] = -1;
}
path[0] = 0;
if(HamiltonianCycle::checkHamiltonianCycle(Matrix, path, 1)==false){
path.resize(1);
path[0] = 0;
return path;
}
return path;
}