361. Breadth First Order
Starting from vertex 1, print the vertices in breadth-first order: vertex 1, then everything one edge away, then everything two edges away, and so on.
When several neighbours are available, visit the SMALLER vertex number first, so the answer is unique.
Print only the vertices reachable from vertex 1. Anything in a separate component is not visited here.
The queue does the work. Take a vertex from the front, print it, and add its unvisited neighbours to the back. Mark a vertex as visited when you ADD it, not when you take it out, or a vertex with two visited neighbours enters the queue twice.
Constraints - `1 ≤ n ≤ 100000` - `0 ≤ m ≤ 200000` - There are no self-loops and no repeated edges.
Input
The first line contains two integers n and m, the number of vertices and
edges. Each of the next m lines contains two integers u and v, an
undirected edge between those vertices. Vertices are numbered 1 to n.
Output
Print the reachable vertices in breadth-first order from vertex 1, separated by single spaces.