1. All Simple Paths Enumeration (DFS Backtracking)
Intuition
Enumerate all possible simple paths from source to each vertex using backtracking and record minimum path lengths.
Algorithm
- Start DFS at source vertex src with current distance = 0.
- Mark current vertex as visited to prevent simple cycle re-entry.
- For each outgoing edge to an unvisited neighbor, recurse with updated distance.
- Backtrack by unmarking visited to explore alternative paths.
#include <iostream>#include <vector>#include <algorithm> using namespace std; const int INF = 1e8; void dfs(int u, int currentDist, const vector<vector<pair<int, int>>>& adj, vector<bool>& visited, vector<int>& minDist) { minDist[u] = min(minDist[u], currentDist); visited[u] = true; for (const auto& edge : adj[u]) { int v = edge.first; int w = edge.second; if (!visited[v]) { dfs(v, currentDist + w, adj, visited, minDist); } } visited[u] = false;} int main() { int V = 4; vector<vector<int>> edges = {{0, 1, 4}, {0, 2, 5}, {1, 2, -3}, {2, 3, 2}}; int src = 0; vector<vector<pair<int, int>>> adj(V); for (const auto& e : edges) { adj[e[0]].push_back({e[1], e[2]}); } vector<int> minDist(V, INF); vector<bool> visited(V, false); dfs(src, 0, adj, visited, minDist); cout << "Shortest distances: "; for (int d : minDist) cout << d << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V!) - Space complexity:
O(V)