i'm trying to understand how this algorithm works.
given a question to search the paths from a source s to all the vertices in the graph ,
I thought that i have to proceed as follows:
if no cycle in the graph:
topological sort of the graph
one iteration to calculate the shortest path
else if there is a cycle in the graph:
put s in the queue
v=q.deque
while q is not empty
relax v
My question are :
Is my proceeding good or i have to change it.
When i must check that there is a negative cycle? Thank you
Your code for the acyclic one seems correct but depends on what do you mean by
one iteration to calculate the shortest path.. If the graph is acyclic (i.e., a DAG) then topological sort will allow us to visit each vertexvonce (after examining all of its predecessors) and updatedist[v]to its minimum distance. This is done in linear time O(V+E). So your DAG algorithm should look somehow similar to thisFor the code of directed cyclic graphs (with no negative cycles), you are not relaxing an edge and not updating/checking its end points.. I am not familiar with the queued version of the BF algorithm. All I can say is that you need to make sure that a vertex
vis in the queue whenever you realize that one of its predecessors (i.e.u) is not done yet. So your code shouldenqueueanddequeuesome vertices under certain conditions (while relaxing the edges). I think you already know the non-queued version of the algorithm which is obvious.BF algorithm over a source
sreturns either the shortest paths fromsto every other vertex or a failure indicating that there is a negative cycle. Following execution, If there is an edge that is not relaxed then there is a negative cycle.