Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of paths between two nodes in a DAG

I want to find number of paths between two nodes in a DAG. O(V^2) and O(V+E) are acceptable.

O(V+E) reminds me to somehow use BFS or DFS but I don't know how. Can somebody help?

like image 748
Saiiiira Avatar asked Mar 02 '11 07:03

Saiiiira


People also ask

How do I find the number of paths in a DAG?

The number of distinct paths from node u to v is the sum of distinct paths from nodes x to v, where x is a direct descendant of u.

How do you find the path between two nodes on a graph?

Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as a source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false.

What is the maximum number of paths between 2 nodes of a tree with n nodes?

A tree with N vertices (or nodes) has N-1 edges, and since in a tree there is always a unique path between two vertices, and the total number of paths equals N(N-1)/2.

Can a directed acyclic graph have an exponential number of paths connecting two nodes?

For a directed acyclic graph with N number of nodes, an exponential number of paths are possible between any two given nodes and, thus, it is not feasible to compute every path and find the shortest ones in polynomial time to generate a set of all edges that contribute or make any of the shortest paths.


2 Answers

The number of distinct paths from node u to v is the sum of distinct paths from nodes x to v, where x is a direct descendant of u.

Store the number of paths to target node v for each node (temporary set to 0), go from v (here the value is 1) using opposite orientation and recompute this value for each node (sum the value of all descendants) until you reach u.

If you process the nodes in topological order (again opposite orientation) you are guaranteed that all direct descendants are already computed when you visit given node.

Hope it helps.

like image 168
stalker Avatar answered Sep 21 '22 23:09

stalker


Do a topological sort of the DAG, then scan the vertices from the target backwards to the source. For each vertex v, keep a count of the number of paths from v to the target. When you get to the source, the value of that count is the answer. That is O(V+E).

like image 21
Jeremiah Willcock Avatar answered Sep 21 '22 23:09

Jeremiah Willcock