1. Backtracking Hamiltonian-Dual Edge Trail Search
Intuition
Use backtracking to find an edge-disjoint walk of length E visiting every edge once.
Algorithm
- From each candidate starting vertex, attempt a recursive DFS.
- Mark each edge as used when crossed.
- If the path length reaches total edges E, check if start == end for circuit.
- Backtrack and reset used edge flags.
#include <iostream>#include <vector>#include <map> using namespace std; bool dfs(int u, int count, int totalE, vector<vector<int>>& adj, map<pair<int, int>, int>& edgeCount, int startNode, bool& isCircuit) { if (count == totalE) { if (u == startNode) isCircuit = true; return true; } for (int v : adj[u]) { pair<int, int> e = {min(u, v), max(u, v)}; if (edgeCount[e] > 0) { edgeCount[e]--; if (dfs(v, count + 1, totalE, adj, edgeCount, startNode, isCircuit)) { return true; } edgeCount[e]++; } } return false;} int isEulerianBruteForce(int V, vector<vector<int>>& adj) { map<pair<int, int>, int> edgeCount; int totalE = 0; for (int u = 0; u < V; ++u) { for (int v : adj[u]) { if (u < v) { edgeCount[{u, v}]++; totalE++; } } } if (totalE == 0) return 2; for (int i = 0; i < V; ++i) { bool isCircuit = false; auto copyEdges = edgeCount; if (dfs(i, 0, totalE, adj, copyEdges, i, isCircuit)) { return isCircuit ? 2 : 1; } } return 0;} int main() { int V = 5; vector<vector<int>> adj = {{1, 2}, {0, 2}, {0, 1, 3, 4}, {2, 4}, {2, 3}}; cout << "Eulerian Status: " << isEulerianBruteForce(V, adj) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V!) - Space complexity:
O(E)