Finding all paths between two nodes on a DAG

喜夏-厌秋 提交于 2019-12-10 19:38:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!