Breadth-first search

Starting at A, list visited vertices. Process each vertex’s neighbors alphabetically and treat the edges as undirected.

Examples

Example 1

Input
Edges A-B, A-C, B-D
Expected output
A, B, C, D

Example 2

Input
Vertices A, B, C. Edge B-C
Expected output
A

Hints and solution

Hint 1

Enqueue B and C in alphabetical order when both touch A.

Reveal worked answer

For the first graph, A discovers B and C. Visiting B discovers D, which goes behind C. In the disconnected example B and C cannot be reached from A.

Back to the lesson