Give every node its own contact list
A list of edges is like a pile of receipts: to answer "who lives next to house 2?" you would have to read every single one. So reorganise once. Give each house its own contact list, then read each edge and write it into both houses' lists.
After that, the answer to "who lives next door?" is just a look at that house's list, instantly.
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
for neighbours in adj:
neighbours.sort()
return adj- adj[0]
- []
- adj[1]
- []
- adj[2]
- []
- adj[3]
- []
Four houses and no lanes read yet. Every house gets an empty contact list, even one that might stay empty.
The classic slip
The most common bug here is writing the edge into only one of the two lists. Your code still runs, but now house v doesn't know house u exists, and every search that starts from v will miss it.
It is like giving someone your number but never saving theirs. Step through the picture below and watch each edge land in two lists.