Finding all paths between two nodes on a DAG
我有一个具有以下邻接表的DAG
1 2 3 4 5 6 | L | G, B, P G | P, I B | I P | I I | R R | \\ |
我想找到从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 } |
这个问题确实很棘手,因为两个节点之间的可能路径数与节点数成指数关系。因此无法避免出现最坏情况的指数运行时。
所有从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } |