algorithm to enumerate all possible paths
Anyway, I just wondered if there was a way to do this, or maybe this is NP-complete.
I don't believe you can output n!
possible paths in polynomial time. And that's how may you get if each node is connected to each other node.
but the problem is that when you have multiple edges between 2 nodes (like edges F3 and F5 above)
So, you want to consider edges F3
and F5
to be the same, right? It's probably the simplest option to just remove duplicate edges before you call dfs
, then.
because it starts at A and then goes to C and builds those paths, but when the DFS gets back to node B, it then tries to go to C, but C has already been visited so it stops.
Well, let's mark C
as not visited again, then.
void dfs(char at) {
vis[at] = true;
// do stuff with 'at'
vis[at] = false;
}
Here is how you can do it with BFS: the following (python
) functions (modified BFS with a recursive path-finding function between two nodes) can be used to find all possible paths between two nodes in an acyclic graph:
from collections import defaultdict
# modified BFS
def find_all_parents(G, s):
Q = [s]
parents = defaultdict(set)
while len(Q) != 0:
v = Q[0]
Q.pop(0)
for w in G.get(v, []):
parents[w].add(v)
Q.append(w)
return parents
# recursive path-finding function (assumes that there exists a path in G from a to b)
def find_all_paths(parents, a, b):
return [a] if a == b else [y + b for x in list(parents[b]) for y in find_all_paths(parents, a, x)]
For example, with the following graph (DAG) G (by removing the directed cycles and multi-edges from the given graph), given by
G = {'A':['B','C'], 'B':['C'], 'C':['D', 'E', 'F'], 'D':['E'], 'E':['I'], 'F':['G', 'H']}
if we want to find all paths between the nodes 'A'
and 'E'
(using the above-defined functions as find_all_paths(find_all_parents(G, 'A'), 'A', 'E'))
, it will return the following paths, as desired:
# ACDE
# ABCDE
# ACE
# ABCE