Challenge: Who Is Connected to Whom?
Completed
Build an adjacency list for an undirected graph and print each place's neighbours in increasing order, as <place>: <neighbours> (nothing after the colon if it has none).
Input
Line 1: n m – the number of places (numbered 0 to n − 1) and the number of roads. Then m lines a b: a two-way road between a and b.
Output
n lines, one per place, from 0 to n − 1.
Example
Input
4 3 0 1 0 2 2 3
Output
0: 1 2 1: 0 2: 0 3 3: 2
Editor
Python
Hints
g = [[] for _ in range(n)]
A two-way road adds b to a's list and a to b's list.
Solution explanation
An adjacency list uses O(V + E) memory – only the roads that exist.
Show solution
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a].append(b)
g[b].append(a)
for v in range(n):
print(f"{v}: " + " ".join(map(str, sorted(g[v])))) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module