Daily iOS
CS fundamentals and algorithms

Shortest path with BFS

A home decor recommender follows a graph of room-to-room connections to find the minimum number of moves. When every edge costs the same, why does BFS guarantee the shortest path?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

BFS uses a queue, so it finishes every node at distance 0, then distance 1, then distance 2, and never reaches distance k+1 before distance k is done. That's why the distance at which you first reach a node is the minimum number of edges to it.

Share a question