Data Structures and Algorithms
In a graph whose edges have no weights, you want to find the smallest number of edges from a starting vertex to every other vertex. Which pair of search method and data structure is suitable?
- ABreadth-first search with a queue
- BDepth-first search with a stack
- CBreadth-first search with a stack
Show answer and explanation
Answer: A. Breadth-first search with a queue
Breadth-first search visits vertices in order of distance: first those one edge from the start, then those two edges away, and so on. Adding each newly found vertex to the back of a queue and taking vertices from the front preserves this nearest-first order, so the number of edges when a vertex is first reached is the shortest. Depth-first search (using recursion or a stack) goes as far as it can along one path, so it may first reach a vertex by a roundabout route, and shortest distances are not guaranteed. Using a stack instead of a queue turns the traversal into something close to depth-first search.
- A. Correct. A queue makes the search visit vertices nearest-first, which gives the smallest number of edges.
- B. Depth-first search can first reach a vertex by a roundabout route, so it does not guarantee shortest distances.
- C. With a stack, the most recently found vertex is examined first, so vertices are no longer visited nearest-first.