Created
November 30, 2018 18:01
-
-
Save sjhalayka/3b6b5c6ab9d72133423b565986a52580 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| bool are_connected(size_t index0, size_t index1, const vector< vector<bool> > &graph) | |
| { | |
| if (graph[index0][index1] && graph[index1][index0]) | |
| return true; | |
| return false; | |
| } | |
| bool is_cycle_hamiltonian(const vector<size_t> &cycle, const vector< vector<bool> > &graph) | |
| { | |
| if (cycle.size() < 2) | |
| return false; | |
| if (cycle[0] != 0 || cycle[cycle.size() - 1] != 0) | |
| return false; | |
| for (size_t i = 0; i < cycle.size() - 1; i++) | |
| { | |
| bool conn = are_connected(cycle[i], cycle[i + 1], graph); | |
| if (false == conn) | |
| return false; | |
| } | |
| return true; | |
| } | |
| // ... | |
| vector<size_t> cycle(vertices.size(), 0); | |
| for (size_t i = 0; i < cycle.size(); i++) | |
| cycle[i] = i; | |
| cycle.push_back(0); | |
| while (1) | |
| { | |
| random_shuffle(cycle.begin() + 1, cycle.end() - 1); | |
| for (size_t i = 0; i < cycle.size() - 2; i++) | |
| { | |
| if (false == are_connected(cycle[i], cycle[i + 1], graph)) | |
| { | |
| bool found_swap = false; | |
| for (size_t j = i + 2; j < cycle.size() - 1; j++) | |
| { | |
| if (true == are_connected(cycle[i], cycle[j], graph)) | |
| { | |
| found_swap = true; | |
| size_t temp = cycle[i + 1]; | |
| cycle[i + 1] = cycle[j]; | |
| cycle[j] = temp; | |
| break; | |
| } | |
| } | |
| if (false == found_swap) | |
| break; | |
| } | |
| } | |
| if (true == is_cycle_hamiltonian(cycle, graph)) | |
| { | |
| ofstream out_file("cycle.txt"); | |
| for (size_t i = 0; i < cycle.size(); i++) | |
| out_file << cycle[i] << endl; | |
| //cout << endl; | |
| break; | |
| } | |
| else | |
| cout << "false" << endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment