Templates
Template: with — beginners get stuck here before they can attempt BFS / DFS.
Mark when done:
with — beginners get stuck here before they can attempt BFS / DFS.
from collections import defaultdict
def build_graph(edges, n_nodes=None, directed=False):
"""Convert an edge list to an adjacency list.
Args:
edges: list of [u, v] pairs. For weighted graphs, pass [u, v, w].
n_nodes: optional number of nodes; if provided, ensures isolated nodes
(nodes with no edges) are still present in the adjacency dict.
directed: True for directed graphs (one-way edges).
Returns:
defaultdict(list) where graph[u] = list of neighbours.
"""
graph = defaultdict(list)
if n_nodes is not None:
for i in range(n_nodes):
graph[i] = []
for edge in edges:
if len(edge) == 2:
u, v = edge
graph[u].append(v)
if not directed:
graph[v].append(u)
elif len(edge) == 3:
u, v, w = edge
graph[u].append((v, w))
if not directed:
graph[v].append((u, w))
return graph