Given an unweighted undirected graph with n vertices (labeled 0 to n-1) and a list of edges where edges[i] = [u, v], find the minimum distance (number of edges) from vertex 0 to every other vertex using BFS.
Return an array dist of length n where dist[i] is the minimum distance from vertex 0 to vertex i. Use -1 if a vertex is unreachable.
Example
Input: n = 5, edges = [[0,1],[0,2],[1,3],[2,4]] Output: [0, 1, 1, 2, 2] Explanation: - 0 → 0: distance 0 - 0 → 1: distance 1 - 0 → 2: distance 1 - 0 → 1 → 3: distance 2 - 0 → 2 → 4: distance 2
Constraints
2 <= n <= 10001 <= edges.length <= 50000 <= u, v < n- No self-loops or duplicate edges.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check