Algorithms and Data Structures · Middle · Question 28 of 75

Why does BFS find the shortest path in an unweighted graph?

Explanation

The queue processes all vertices at distance 1, then distance 2, and so on. The first time BFS reaches a vertex, it does so by a shortest path. With weighted edges you need Dijkstra instead.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 28

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz