3

I have just seen this video: https://youtu.be/2E7MmKv0Y24?t=1335
It talks about an algorithm that finds the shortest distance between a source and a given vertex in a DAG:

1.Sort the graph in topological order and express the graph in its linear form
2.Initialize all of the vertex to infinity except the source, which is initialized to 0
3.Iterate from the source to the rightmost vertex. For every vertex u, update the distance of all of its neighbor v to min((distance between source and v), (distance between source and u) + (distance between u and v))

At about 22:00, the professor said that this algorithm works for negative edges but the graph cannot contain cycle, but i think the algorithm works for graphs that contain non-negative cycle. Am I right?

1
  • 1
    Instead of posting the video, could you put its content here in text-form? What algorithm is he talking about? Commented Nov 19, 2019 at 8:36

2 Answers 2

1

..., but i think the algorithm works for graphs that contain non-negative cycle. Am I right?

Yes, you're right. See this post for more information.

Another question is why do I need to topologically sort the array first? Why can't I just loop through every neighbour and calculate the distance to them?

If I understood the question correctly you can't go to just any next node because there could be a shorter way to this node using another node first (e.g. the cost to reach a node is 5 and there is another way to the node using two nodes that uses a cost of 1 + 1 = 2; If you don't sort first in this case you would use the wrong path)

Sign up to request clarification or add additional context in comments.

Comments

0

I realised that I was not correct apparently. If the graph has cycles then topological sort isn't possible.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.