0

I know that it can be done in O(V+E) using topological sorting. But I think it can also be done in the same complexity using BFS.

Dominique Fortin
  • 2,212
  • 15
  • 20
Aditya Joshee
  • 137
  • 1
  • 3
  • 11
  • Can you elaborate more what do you mean by (in the most optimal way)? If what you mean is the complexity then yes. A topological sort is the application of DFS that is why it has a complexity of O(V+E). I think it is more natural to ask "can we do a topological sort using BFS?". This question has already been asked. – Abdulhakeem Apr 25 '17 at 03:58
  • What I meant was can we just use BFS instead of visiting the nodes in topological order. – Aditya Joshee Apr 25 '17 at 09:59

2 Answers2

0

The topological sort is nothing except that it is one DFS run. Then as each vertex is finished you put it onto the front of a linked list. It has a running time of O(V+E). As I said before, I think it is more natural here to ask "can we do a topological sort using BFS?". This has already been asked and answered.

If what you mean is mere BFS, then I would say no. Have a look to this example. A topological sort is a linear ordering of all its vertices such that if graph G contains an edge (u, v), then u appears before v in the ordering. You can see in that example there is an edge from c to d but d appears before c. I think you can update BFS to find the topological sort but again it has the same complexity as running DFS. I would recommend you to have a look at this post Using BFS for topological sort

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Abdulhakeem
  • 153
  • 7
  • Let's forget about topological sort for some time. If I use breadth first traversal for a DAG, starting with a source node s, then I can find the shortest distance to all other nodes in O(V+E) time by maintaining a distance array (initialized with infinity) and updating it when we get a value smaller than the currently stored value for a node. So coming back to my original question, isn't this approach of same complexity as using a topological order for traversing nodes in a DAG to find shortest paths? – Aditya Joshee Apr 25 '17 at 17:32
  • I also have a same question, why can't we simply use BFS and find the shortest distance from the source vertex to all other vertices in a DAG? – user3260035 Jun 06 '21 at 05:08
0

Using simple BFS is not optimal because if the node, say(A), is already updated from INT_MAX to some x and pushed into the queue, and we found a way to reach A with some value less than x, then we update it and again push into the queue now here we can reduce the time complexity slightly if A is already in the queue, we dont push it ,but what if A is not in the queue but already processed once then we have to push A again and all the adjacent nodes have to get processed again.

To avoid this repetation we travel in topologically sorted order so we can avoid this kind of looping.