39
$\begingroup$

Can anyone suggest me a linear time algorithm that takes as input a directed acyclic graph $G=(V,E)$ and two vertices $s$ and $t$ and returns the number of simple paths from $s$ to $t$ in $G$.
I have an algorithm in which I will run a DFS(Depth First Search) but if DFS finds $t$ then it will not change the color(from white to grey) of any of the nodes which comes in the path $s \rightsquigarrow t$ so that if this is the subpath of any other path then also DFS goes through this subpath again.For example consider the adjacency list where we need to find the number of paths from $p$ to $v$.
$$\begin{array}{|c|c c c|} \hline p &o &s &z \\ \hline o &r &s &v\\ \hline s &r \\ \hline r &y \\ \hline y &v \\ \hline v &w \\ \hline z & \\ \hline w &z \\ \hline \end{array}$$ Here DFS will start with $p$ and then lets say it goes to $p \rightsquigarrow z$ since it doesnot encounter $v$ DFS will run normally.Now second path is $psryv$ since it encounter $v$ we will not change the color of vertices $s,r,y,v$ to grey.Then the path $pov$ since color of $v$ is still white.Then the path $posryv$ since color of $s$ is white and similarly of path $poryv$.Also a counter is maintained which get incremented when $v$ is encountered.

Is my algorithm correct? if not, what modifications are needed to make it correct or any other approaches will be greatly appreciated.

Note:Here I have considered the DFS algorithm which is given in the book "Introduction to algorithms by Cormen" in which it colors the nodes according to its status.So if the node is unvisited , unexplored and explored then the color will be white,grey and black respectively.All other things are standard.

$\endgroup$
2
  • $\begingroup$ Related question. $\endgroup$
    – Raphael
    Commented Aug 8, 2012 at 1:01
  • 4
    $\begingroup$ Note that all paths in a directed acyclic graph are necessarily simple (by virtue of acyclicity). $\endgroup$
    – Noldorin
    Commented Nov 26, 2012 at 23:40

4 Answers 4

43
$\begingroup$

Your current implementation will compute the correct number of paths in a DAG. However, by not marking paths it will take exponential time. For example, in the illustration below, each stage of the DAG increases the total number of paths by a multiple of 3. This exponential growth can be handled with dynamic programming.

dag

Computing the number of $s$-$t$ paths in a DAG is given by the recurrence, $$\text{Paths}(u) = \begin{cases} 1 & \text{if } u = t \\ \sum_{(u,v) \in E} \text{Paths}(v) & \text{otherwise.}\\ \end{cases}$$

A simple modification of DFS will compute this given as

def dfs(u, t):
    if u == t:
        return 1
    else:
        if not u.npaths:
            # assume sum returns 0 if u has no children
            u.npaths = sum(dfs(c, t) for c in u.children)
        return u.npaths

It is not difficult to see that each edge is looked at only once, hence a runtime of $O(V + E)$.

$\endgroup$
5
  • $\begingroup$ I understood your algorithm and it can be made little more efficient by using dynamic programming since same recursive calls are called many times so its better to save.Right?? $\endgroup$
    – Saurabh
    Commented Aug 8, 2012 at 14:17
  • 1
    $\begingroup$ @SaurabhHota, it is using dynamic programming. The first time the vertex $u$ is encountered, it computes the number of paths it has to $t$. This is stored in u.npaths. Each subsequent call to $u$ will not recompute its number of paths, but simply return u.npaths. $\endgroup$ Commented Aug 8, 2012 at 14:43
  • 1
    $\begingroup$ For such graphs, isn't the answer just m^n where m is the number of nodes in a column (3 here) and n is the number of columns excluding s,t (4 here). output is 3^4 = 81 for the example graph. $\endgroup$
    – mrk
    Commented Feb 10, 2015 at 0:16
  • $\begingroup$ @saadtaame, sure; however, my intent was to merely showcase exponential increase as the "length" of a graph grows. Of course for that highly structured graph you can count in closed form while the algorithm listed works for all graphs. $\endgroup$ Commented Feb 10, 2015 at 1:19
  • 3
    $\begingroup$ The $O(V+E)$ running time assumes that you can perform the necessary additions in constant time, but the numbers being added can have $\Theta(V)$ bits in the worst case. If you want the exact number of paths, the running time (counting bit operations) is actually $O(VE)$. $\endgroup$
    – JeffE
    Commented Feb 18, 2015 at 14:40
16
$\begingroup$

You only need to notice that the number of paths from one node to the target node is the sum of the number of paths from its children to the target. You know that this algorithm will always stop because your graph doesn't have any cycles.

Now, if you save the number of paths from one node to the target as you visit the nodes, the time complexity becomes linear in the number of vertices and memory linear in the number of nodes.

$\endgroup$
0
$\begingroup$

The number of paths between any two vertices in a DAG can be found using adjacency matrix representation.

Suppose A is the adjacency matrix of G. Taking Kth power of A after adding identity matrix to it, gives the number of paths of length <=K.

Since the max length of any simple path in a DAG is |V|-1, calculating |V|-1 th power would give number of paths between all pairs of vertices.

Calculating |V|-1 th power can be done by doing log(|V|-1) muliplications each of TC: |V|^2.

$\endgroup$
2
  • $\begingroup$ The question asks for a linear time algorithm. Your algorithm is slower than that. $\endgroup$
    – D.W.
    Commented Feb 15, 2016 at 7:04
  • $\begingroup$ @Vivek can you mention a reference for the theorems in your answer? $\endgroup$
    – Hamideh
    Commented Mar 24, 2017 at 3:54
0
$\begingroup$

As Nicholas' answer mentioned, you can use a top-down recursive approach, and use memoïzation to prevent solving overlapping subproblems. However, you can also use a bottom-up approach, which counts the number of paths to the target from all nodes in the graph, with the same complexity of $O(V+E)$.

def dfs(G, s, t):
    fifo = Queue()
    fifo.put(s)
    n_paths = [0] * len(G.V)
    n_paths[s] = 1
    while not fifo.empty():
        current = fifo.get()
        for p in G.parents(current):
            n_paths[p] += n_paths[current]
            if not p.already_visited:
                fifo.put(p)
                p.already_visited = True
    return n_paths[t]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.