-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0005_HamiltonianPathAndCycle.cc
114 lines (103 loc) · 2.47 KB
/
0005_HamiltonianPathAndCycle.cc
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "../Headers/0003_Graph/0005_HamiltonianPathAndCycle.h"
using namespace std;
namespace HamiltonianPathAndCycle
{
Node::Node(int value)
{
this->data = value;
this->isVisited = false;
}
// Graph Private Member Methods
Node* Graph::MakeOrFindNode(int value)
{
Node* node = nullptr;
if (this->_nodeMap.find(value) == this->_nodeMap.end())
{
node = new Node(value);
this->_nodeMap[value] = node;
}
else
{
node = this->_nodeMap[value];
}
return node;
}
bool Graph::IsSafe(Node* nodeU, Node* nodeV)
{
if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end())
{
return false;
}
if (nodeV->isVisited == true)
{
return false;
}
return true;
}
bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU)
{
if (this->_visitedNodeCount == this->_nodeMap.size())
{
if (this->_adjlist[nodeU].find(this->_startingNode) != this->_adjlist[nodeU].end())
{
this->_isHamiltonianCyclePresent = true;
this->_isHamiltonianPathPresent = true;
return true;
}
this->_isHamiltonianPathPresent = true;
return false;
}
for (auto& nodeV : this->_adjlist[nodeU])
{
if (this->IsSafe(nodeU, nodeV))
{
this->_hamiltonianPath.push_back(nodeV->data);
nodeV->isVisited = true;
this->_visitedNodeCount++;
if (this->HamiltonianCycleAndPathUtil(nodeV))
{
return true;
}
this->_visitedNodeCount--;
nodeV->isVisited = false;
this->_hamiltonianPath.pop_back();
}
}
return false;
}
// Graph Public Member Methods
void Graph::PushUndirectedEdge(int valueU, int valueV)
{
Node* nodeU = this->MakeOrFindNode(valueU);
Node* nodeV = this->MakeOrFindNode(valueV);
this->_adjlist[nodeU].insert(nodeV);
this->_adjlist[nodeV].insert(nodeU);
}
void Graph::PushSingleNode(int valueU)
{
Node* nodeU = this->MakeOrFindNode(valueU);
}
void Graph::FindHamiltonianCycleAndPath()
{
this->_isHamiltonianCyclePresent = false;
this->_isHamiltonianPathPresent = false;
this->_hamiltonianPath = {};
this->_startingNode = this->_nodeMap[0];
this->_hamiltonianPath.push_back(this->_startingNode->data);
this->_startingNode->isVisited = true;
this->_visitedNodeCount = 1;
this->HamiltonianCycleAndPathUtil(this->_startingNode);
}
bool Graph::IsHamiltonianCyclePresent()
{
return this->_isHamiltonianCyclePresent;
}
bool Graph::IsHamiltonianPathPresent()
{
return this->_isHamiltonianPathPresent;
}
vector<int> Graph::GetHamiltonianPath()
{
return this->_hamiltonianPath;
}
}