问题
I have a DAG that has the following adjacency list
L | G, B, P
G | P, I
B | I
P | I
I | R
R | \
I want to find all paths from L
to R
. I know that I have to do some kind of DFS, and this is what I have so far. (Excuse the 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)
for (neighbor in G[vertex].neighbors) {
fringe.push(neighbor)
}
visited.add(vertex)
}
}
return output
}
The output of dfs(G, "L")
is [ 'L', 'P', 'I', 'R', 'B', 'G' ]
which is indeed a depth first traversal of this graph, but not the result I'm looking for. After doing some searching, I realize there may be a recursive solution, but there were some comments about this problem being "NP-hard" and something about "exponential paths" which I don't understand.
回答1:
The problem is indeed np-hard because the number of possible paths between two nodes is exponential to the number of nodes. so no way around having a worst-case exponential runtime.
回答2:
All paths with start head
to vertex vertex
can be split into paths with heads head||v
where v
is adjacent to final vertex of head
, unless final vertex of head
is already 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);
}
来源:https://stackoverflow.com/questions/43072300/finding-all-paths-between-two-nodes-on-a-dag