15

Given an unweighted DAG (directed acyclic graph) $D = (V,A)$ and two vertices $s$ and $t$, is it possible to find the shortest and longest path from $s$ to $t$ in polynomial time? Path lengths are measured by the number of edges.

I am interested in finding the range of possible path lengths in polynomial time.

Ps., this question is a duplicate of the StackOverflow question Longest path in a DAG.

robowolverine
  • 347
  • 1
  • 2
  • 8

2 Answers2

13

For the shortest path problem, if we do not care about weights, then breadth first search is a surefire way. Otherwise Dijkstra's algorithm works as long as there are no negative edges.

For longest path, you could always do Bellman-Ford on the graph with all edge weights negated. Recall that Bellman-Ford works as long as there are no negative weight cycles, and therefore works with any weights on a DAG.

Sasho Nikolov
  • 2,587
  • 17
  • 20
Joey Eremondi
  • 30,277
  • 5
  • 67
  • 122
8

Let $n = |V(G)|$ and $m = |E(G)|$. Let $w(a \to b)$ denote the weight of the edge $(a \to b)$. Suppose that you want to find the minimum and maximum path cost from $s$ to $t$.

Starting from $b := t$, perform the following:

  1. If $b$ has already been visited, return the already computed $\min(b)$ and $\max(b)$. Otherwise mark $b$ as visited.

  2. Determine and record $\min(b)$ and $\max(b)$ as follows.

    • If $b = s$, store $\min(s) := \max(s) := 0$.
    • Else set $$\begin{align*}\min(b) &:= \min_{a \to b} \Bigl[ w(a \to b) + \min(a) \Bigr] \\ \max(b) &:= \max_{a \to b} \Bigl[ w(a \to b) + \max(a) \Bigr]\end{align*}$$ ignoring vertices for which $\min(a) = \max(a) = \mathrm{inaccessible}$. When computing minimum and maximum over an empty set of edges (no inbound edges to $b$ at all, or all ignored), set $\min(b) := \max(b) := \mathrm{inaccessible}$.

You should be able to prove that this algorithm runs in time $O(m)$, neglecting the time required to initialise all of the vertex variables.

cody
  • 8,427
  • 33
  • 64
Niel de Beaudrap
  • 4,241
  • 1
  • 18
  • 32