简体   繁体   中英

Finding number of paths between two nodes in a directed acyclic graph

My idea of solving this problem is to adjust DFS so that it stops when we hit the destination node, then set up a counter that adds up all of the neighbors of the starting node, then the neighbors of the starting node and its neighrbours recursively.

I'm just wondering if this will only count the paths from the source to the destination, and not any stray paths that don't lead to the destination node.

Thank you for the help.

You can use dynamic programming. You have a directed acyclic graph so you have a node (say s) with no arcs pointing into s. You also have a node (say t) that has no arcs pointing out of t. Because it is acyclic, you can use a topological sorting algorithm to find an ordering of the nodes such that every arc points away from s and towards t.

So start at s. The number of paths from s to s is 1, the empty path. Because the graph is acyclic, s must have a neighbour u such that the only arc pointing into u is su. Now you just repeat. In general, for a node w that has arcs from v1,...vk pointing into it. Then the number of paths from s to w is just the sum of the number of sv1 paths, ..., svk paths.

This is in the case of a single arc between each node. If there are multiple arcs you multiply so it would be (number of v1w arcs)(number of sv1paths) + ... + (number of vkw arcs)(number of svk paths)

And at each step you can use the fact that it is acyclic to find the node w such that you have already calculated all the sv1 to svk paths.

I would use BFS.

Let's call the source node s and the target node t .

When you BFS starting from s , all the paths with length 1 will be found and put into a queue. You can, then, take the first element of the queue (call it u ) and find all the paths of size 2 ( s -> u -> ... ). Repeat the same thing for each distance, until you find all paths of all lengths from s to t .

A trick to speed it up would be: after you exhausted all the paths of a node w , store how many paths from w to t there are, and when another node (above w ) reach w , you won't need to recompute all the paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM