algorithm - Finding all paths between two nodes on a DAG -
i have dag has following adjacency list
l | g, b, p g | p, b | p | i | r r | \
i want find paths l
r
. know have kind of dfs, , have far. (excuse javascript)
function dfs(g, start_vertex) { const fringe = [] const visited = new set() const output = [] fringe.push(start_vertex) while (fringe.length != 0) { const vertex = fringe.pop() if (!visited.has(vertex)) { output.push(vertex) (neighbor in g[vertex].neighbors) { fringe.push(neighbor) } visited.add(vertex) } } return output }
the output of dfs(g, "l")
[ 'l', 'p', 'i', 'r', 'b', 'g' ]
indeed depth first traversal of graph, not result i'm looking for. after doing searching, realize there may recursive solution, there comments problem being "np-hard" , "exponential paths" don't understand.
all paths start head
vertex vertex
can split paths heads head||v
v
adjacent final vertex of head
, unless final vertex of head
vertex
: (pseudo-javascript, can have syntax problems)
function print_all_rec(g, head, vertex){ if(head[head.length-1] == vertex){ print(head); //we're here return; } for(v in head[head.length-1].neighbors){ var newhead = head; newhead.append(v); print_all_rec(g, newhead, vertex); } } function print_all_routes(g, from, to){ var start = []; start.append(from); print_all_rec(g, start, to); }
Comments
Post a Comment