Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all paths between two nodes on a DAG

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.

like image 365
Carpetfizz Avatar asked Oct 15 '25 15:10

Carpetfizz


2 Answers

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.

like image 113
Amnon Avatar answered Oct 17 '25 16:10

Amnon


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);
}
like image 35
Abstraction Avatar answered Oct 17 '25 17:10

Abstraction



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!