WorkspaceProblem lab
ALGORITHM VISUALIZER

Unweighted Graph Distances

Opening the interactive workspace…

Understanding Unweighted Graph Distances

Return the fewest edges from source to every vertex in an undirected graph. Use -1 for unreachable vertices.

How it works

A FIFO queue discovers vertices in increasing distance, so their first assigned distances are final.

Build an undirected adjacency list and enqueue source at distance zero. Process queued vertices in arrival order. Assign each undiscovered neighbor the current distance plus one before enqueuing.

Try an example

Input: n = 5, edges = [[0, 1], [0, 2], [1, 3]], source = 0

Output: [0, 1, 1, 2, -1]

A FIFO queue discovers vertices in increasing distance, so their first assigned distances are final.

Constraints

  • 1–16 vertices numbered 0 through n - 1; at most 48 edges [u, v].
  • Source and all edge endpoints must be valid vertices.
  • Self-loops and repeated edges are allowed; the source distance is 0.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity