Breadth-first visit order

Breadth-first search visits the vertices ring by ring around the start. Your program prints the order in which it visits the vertices reachable from vertex 1.

What to build

A program that prints the BFS visit order from vertex 1.

Requirements

  • Read n and m, then m edges u v of an undirected graph on the vertices 1 to n.
  • Start the search at vertex 1. Always take the neighbours of a vertex in increasing order.
  • Print the vertices in the order they are visited, on one line separated by spaces. Vertices that cannot be reached from 1 are not printed.

Input

The first line has n and m. Each of the next m lines has an edge.

Output

One line.

Constraints

1 ≤ n ≤ 30; 0 ≤ m ≤ 60.

Example

Input:

5 4
1 2
1 3
2 4
3 5

Output:

1 2 3 4 5

Why it works

A queue serves vertices in the order they were found, so every vertex at distance d is visited before any vertex at distance d + 1. Taking neighbours in increasing order makes the result unique, and the visited marks make each vertex appear once.

Examples

Example 1 · Input
5 4
1 2
1 3
2 4
3 5
Expected output
1 2 3 4 5
Example 2 · Input
4 3
1 4
4 3
3 2
Expected output
1 4 3 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep a list of neighbours for each vertex and sort it, so that neighbours are taken in increasing order.

Hint 2

Use a deque as the queue: take a vertex from the left, append its unvisited neighbours on the right.

Hint 3

Mark a vertex as visited when you add it to the queue.

Solution

Show one correct solution (try it yourself first)
from collections import deque

n, m = map(int, input().split())
adj = {v: [] for v in range(1, n + 1)}
for _ in range(m):
    u, v = map(int, input().split())
    adj[u].append(v)
    adj[v].append(u)
seen = {1}
queue = deque([1])
order = []
while queue:
    v = queue.popleft()
    order.append(v)
    for w in sorted(adj[v]):
        if w not in seen:
            seen.add(w)
            queue.append(w)
print(*order)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Searching a graph: BFS and DFS →