1. Backtracking Path Search with Edge Set
Intuition
Explore all permutations of edge traversals using backtracking, rolling back on dead ends until a complete length-E trail is found.
Algorithm
- Identify start vertex.
- Recursively explore unused incident edges.
- Track path in an array.
- If path length reaches E + 1, return success.
- Backtrack if dead end reached before consuming all E edges.
#include <iostream>#include <vector>#include <map> using namespace std; bool backtrack(int u, int count, int totalE, const vector<vector<int>>& adj, map<pair<int, int>, int>& edgeCount, vector<int>& path) { if (count == totalE) return true; for (int v : adj[u]) { pair<int, int> e = {min(u, v), max(u, v)}; if (edgeCount[e] > 0) { edgeCount[e]--; path.push_back(v); if (backtrack(v, count + 1, totalE, adj, edgeCount, path)) return true; path.pop_back(); edgeCount[e]++; } } return false;} vector<int> findEulerianTrailBacktracking(int V, const vector<vector<int>>& edges) { vector<vector<int>> adj(V); map<pair<int, int>, int> edgeCount; vector<int> degree(V, 0); for (const auto& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); edgeCount[{min(e[0], e[1]), max(e[0], e[1])}]++; degree[e[0]]++; degree[e[1]]++; } int start = 0; for (int i = 0; i < V; ++i) { if (degree[i] % 2 != 0) { start = i; break; } } vector<int> path = {start}; backtrack(start, 0, edges.size(), adj, edgeCount, path); return path;} int main() { int V = 4; vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}}; auto trail = findEulerianTrailBacktracking(V, edges); cout << "Trail: "; for (int v : trail) cout << v << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V!) - Space complexity:
O(V + E)