Pseudo Code
Lesson 4 of 9 in Coddy's Depth-First Search - Graph Algorithms course.
buildAdjacency(n, edges):
adj = n empty lists
for each pair (u, v) in edges:
adj[u].add(v)
adj[v].add(u) # undirected
sort every adj[i] ascending
dfs(n, edges, start):
build adjacency
visited = all false
stack = [start]
order = []
while stack not empty:
node = stack.pop()
if visited[node]: continue
visited[node] = true
order.add(node)
for nb in adj[node] from last to first:
if not visited[nb]: stack.push(nb)
return order- The adjacency list turns the flat edge array into, for each vertex, the sorted list of its neighbors.
- Pushing neighbors last-to-first makes the stack hand back the smallest neighbor first, so the visit order is deterministic.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Depth-First Search - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)