TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
hamiltons_cycle.cpp
Go to the documentation of this file.
1
18#include <cassert>
19#include <iostream>
20#include <vector>
21
30bool hamilton_cycle(const std::vector<std::vector<bool>> &routes) {
31 const size_t n = routes.size();
32 // height of dp array which is 2^n
33 const size_t height = 1 << n;
34 std::vector<std::vector<bool>> dp(height, std::vector<bool>(n, false));
35
36 // to fill in the [2^i, i] cells with true
37 for (size_t i = 0; i < n; ++i) {
38 dp[1 << i][i] = true;
39 }
40 for (size_t i = 1; i < height; i++) {
41 std::vector<size_t> zeros, ones;
42 // finding positions with 1s and 0s and separate them
43 for (size_t pos = 0; pos < n; ++pos) {
44 if ((1 << pos) & i) {
45 ones.push_back(pos);
46 } else {
47 zeros.push_back(pos);
48 }
49 }
50
51 for (auto &o : ones) {
52 if (!dp[i][o]) {
53 continue;
54 }
55
56 for (auto &z : zeros) {
57 if (!routes[o][z]) {
58 continue;
59 }
60 dp[i + (1 << z)][z] = true;
61 }
62 }
63 }
64
65 bool is_cycle = false;
66 for (size_t i = 0; i < n; i++) {
67 is_cycle |= dp[height - 1][i];
68 if (is_cycle) { // if true, all subsequent loop will be true. hence
69 // break
70 break;
71 }
72 }
73 return is_cycle;
74}
75
81static void test1() {
82 std::vector<std::vector<bool>> arr{
83 std::vector<bool>({true, true, false, false}),
84 std::vector<bool>({false, true, true, false}),
85 std::vector<bool>({false, false, true, true}),
86 std::vector<bool>({false, false, false, true})};
87
88 bool ans = hamilton_cycle(arr);
89 std::cout << "Test 1... ";
90 assert(ans);
91 std::cout << "passed\n";
92}
93
103static void test2() {
104 std::vector<std::vector<bool>> arr{
105 std::vector<bool>({true, true, false, false}),
106 std::vector<bool>({false, true, true, true}),
107 std::vector<bool>({false, false, true, false}),
108 std::vector<bool>({false, false, false, true})};
109
110 bool ans = hamilton_cycle(arr);
111
112 std::cout << "Test 2... ";
113 assert(!ans); // not a cycle
114 std::cout << "passed\n";
115}
116
122static void test3() {
123 std::vector<std::vector<bool>> arr{
124 std::vector<bool>({true, true, true, true}),
125 std::vector<bool>({true, true, true, true}),
126 std::vector<bool>({true, true, true, true}),
127 std::vector<bool>({true, true, true, true})};
128
129 bool ans = hamilton_cycle(arr);
130
131 std::cout << "Test 3... ";
132 assert(ans);
133 std::cout << "passed\n";
134}
135
142int main(int argc, char **argv) {
143 test1();
144 test2();
145 test3();
146 return 0;
147}
int height(node *root)
Definition avltree.cpp:38
int main()
Main function.
static void test3()
static void test2()
bool hamilton_cycle(const std::vector< std::vector< bool > > &routes)
static void test1()
for std::vector