2

I have many questions which related to this topic. I saw somewhere that a topological sorting can be used to find shortest path, and in DAG it can even find shortest weighted paths of all vertex by asking about each vertex whether it's weighted higher than edge plus previous vertex. The point is, I don't understand since we are in DAG why isn't DFS alone enough to find shortest paths. Both weighted and unweighted. I also don't understand why we need a stack in topological sort. If you were to perform a DFS on some DAG. It will automatically produce a topological sort, if you do a pre-order DFS traverse.

bilanush
  • 263
  • 1
  • 8

2 Answers2

1

The only question is in the tile so I'm going to answer that.

A DFS visit from a source $s$ of a unweighted DAG $G$ does not find the shortest paths of $G$ from $s$. As a counter example look at the following graph: counterexample

If vertex $a$ is visited before vertex $b$ you will not necessarily discover the shortest path from $s$ to $b$.

Also, the same example shows that the order in which vertices are considered by a preorder DFS traversal is not necessarily a topological sort. Indeed, if $b$ is visited before $a$ the order would be: $s, b, a$ but there is an edge from $a$ to $b$.

Steven
  • 29,724
  • 2
  • 29
  • 49
1
  1. Why don't we just use DFS to find shortest path in DAG?

For this try to find shortest path from source vertex $0$ to all vertex in following graph.

graph_example

In particular if DFS visits $1$ first from $0$ then it will assign shortest path distance $10$ to $4$ which is wrong.

Vimal Patel
  • 597
  • 2
  • 16