Implement BFS shortest paths with reconstruction
MathWorksSoftware Engineer · Online AssessmentLast updated
This question evaluates understanding of graph traversal via breadth-first search, computation of shortest paths in unweighted graphs, and path reconstruction using parent arrays, assessing algorithmic reasoning and implementation skills in the Coding & Algorithms domain.
Given an unweighted graph with n vertices and m edges represented as an adjacency list, implement breadth-first search (BFS) from a source vertex s to return: (
- an array dist where dist[v] is the length of the shortest path from s to v (or −1 if unreachable); and (
- an array parent to reconstruct one shortest path. Handle disconnected graphs, analyze time and space complexity, and provide code in C, C++, Java, or JavaScript.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.