1. All-Permutations Brute Force Generation
Intuition
Generate all (V - 1)! permutations of vertices 1 to V - 1 and verify whether all consecutive pairs and the wrap-around edge exist.
Algorithm
- Create array [1, 2, ..., V - 1].
- For every permutation of this array:
- Form candidate path [0, p1, p2, ..., p_{V-1}, 0].
- Check if all V edges exist in the graph.
- If valid, return path.
- Return [] if no permutation forms a valid cycle.
#include <iostream>#include <vector>#include <numeric>#include <algorithm> using namespace std; vector<int> hamiltonianCyclePermutations(int V, const vector<vector<int>>& graph) { vector<int> p(V - 1); iota(p.begin(), p.end(), 1); do { bool valid = true; int prev = 0; for (int curr : p) { if (!graph[prev][curr]) { valid = false; break; } prev = curr; } if (valid && graph[prev][0]) { vector<int> cycle = {0}; cycle.insert(cycle.end(), p.begin(), p.end()); cycle.push_back(0); return cycle; } } while (next_permutation(p.begin(), p.end())); return {};} int main() { int V = 5; vector<vector<int>> graph = { {0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0} }; auto cycle = hamiltonianCyclePermutations(V, graph); cout << "Cycle: "; for (int v : cycle) cout << v << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V! * V) - Space complexity:
O(V)