8.2Graph with Adjacency Lists
Depth-first search (DFS)
This lesson is the twin of DFS with a matrix. DFS still dives at once into the first unmarked neighbour it finds and goes back at a dead end. The difference is that the neighbours are found by walking an adjacency list, not by scanning a row. That way each call looks only at the edges of its own vertex.
- How a list is walked in recursive DFS
- How each call remembers where it stopped in its list
- Why DFS with lists takes O(n + e) time
1The idea
dfsVisit(g, u, visited) marks and prints u, then walks the list of u with temp. If the vertex at temp is not marked, it calls itself for it at once. When that call returns, temp moves to the next node and the walk goes on from where it stopped.
What makes this work is that temp is a local variable of each call. Every frame on the call stack keeps the node it is waiting at in the list of its own vertex. In the example, when DFS goes from 4 down to 3 there are six frames on the stack, and each one's temp is at a different node of a different list. In the drawing the caller's temp is shown on the node of the neighbour it went down to.
The output is the same as with the matrix, 0 1 2 5 4 3, because the lists are sorted from smallest to largest. The time changes: there is one call per vertex (n) and each call walks its own list once; the lists add up to 2e nodes. In all, O(n + e). DFS with a matrix looked at n cells in every call, so it took O(n²).
| DFS with a matrix | DFS with lists | |
|---|---|---|
| Neighbours | The n cells of the row are scanned | The d nodes of the list are walked |
| Work per call | O(n) | O(d) |
| Total time | O(n²) | O(n + e) |
| Checked in the sample | 36 cells | 14 nodes |
2Step by step
The drawing walks the sample graph with DFS starting at 0. Faded vertices have not been found yet; u is the vertex of the call running now, and on the right its list being walked (orange). The green ones were printed earlier. The temp label is the node where the caller waits in its list. The call stack is shown under the drawing, the newest call last.
- Start: no vertex is marked.
dfs(&g, 0)is called. dfsVisit(0): 0 is marked and printed. The walk of the list of 0 begins. Output: 0.- The first node in the list of 0 is 1, unmarked. While the
tempof 0 waits at this node,dfsVisit(1)is called. Output: 0 1. - The list of 1 is 0, 2, 4. 0 is marked; at 2,
dfsVisit(2)is called. Output: 0 1 2. - The list of 2 is 1, 5. 1 is marked; DFS goes down to 5. Output: 0 1 2 5.
- The list of 5 is 2, 4. 2 is marked; DFS goes down to 4. Output: 0 1 2 5 4.
- The list of 4 is 1, 3, 5. 1 is marked; DFS goes down to 3. Output: 0 1 2 5 4 3. Every vertex is printed, but there are six calls on the stack.
- The 0 and 4 in the list of 3 are marked: 3 returns. The
tempof 4 moves to 5, which is marked: 4 returns. 5 and 2 return as well. Thetempof 1 moves from 2 to 4; 4 is marked. - 1 returns. The
tempof 0 moves from 1 to 3: 3 is marked. 0 returns too and the stack is empty. - The DFS order is the same as with the matrix: 0 1 2 5 4 3. This time 14 list nodes were looked at in all, instead of 36 cells.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; void dfsVisit(struct Graph* g, int u, bool visited[]) { visited[u] = true; printf("%d ", u); for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) if (!visited[temp->data]) dfsVisit(g, temp->data, visited); // dive into the neighbour} void dfs(struct Graph* g, int start) { bool visited[MAX] = {false}; dfsVisit(g, start, visited);}class Node { int data; Node next; Node(int data) { this.data = data; }} class ListGraph { int n; boolean directed; Node[] adj; ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; } void dfsVisit(int u, boolean[] visited) { visited[u] = true; System.out.print(u + " "); for (Node temp = adj[u]; temp != null; temp = temp.next) if (!visited[temp.data]) dfsVisit(temp.data, visited); // dive into the neighbour } void dfs(int start) { boolean[] visited = new boolean[n]; dfsVisit(start, visited); }}class Node: def __init__(self, data): self.data = data self.next = None class ListGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [None] * n def dfs_visit(self, u, visited): visited[u] = True print(u, end=" ") temp = self.adj[u] while temp is not None: if not visited[temp.data]: self.dfs_visit(temp.data, visited) # dive into the neighbour temp = temp.next def dfs(self, start): visited = [False] * self.n self.dfs_visit(start, visited)The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
One call per vertex (n); each call walks its list once, and the lists add up to 2e nodes.
The visited array holds n elements. In the worst case the call stack goes n calls deep; each frame holds one temp.
In very large graphs the recursion can go deeper than the stack allows. Then DFS is written as a loop with an explicit stack; next to each vertex the stack also keeps the node where its list walk stopped.
4Common mistake
When writing it with a while loop, as in Python, a common mistake is moving temp on only when you dive:
struct Node* temp = g->adj[u];while (temp != NULL) { if (!visited[temp->data]) { dfsVisit(g, temp->data, visited); temp = temp->next; // only moves on here }}If the node in the list is already marked, the if is skipped and temp stays where it is: the loop looks at the same node forever. In the example the first node in the list of 1 is 0, which is marked; the program already hangs at 1. The step forward belongs outside the if, at the end of the loop.
5Try it
If DFS with lists starts at vertex 5 of the sample graph, what is the output?
The answer is A. The list of 5 is 2, 4: DFS goes down to 2. The next unmarked vertex is 1 in the list of 2, 0 in that of 1, 3 in that of 0 and 4 in that of 3. Order: 5 2 1 0 3 4. The second option is the output of BFS.
Show the answer
The answer is A. The list of 5 is 2, 4: DFS goes down to 2. The next unmarked vertex is 1 in the list of 2, 0 in that of 1, 3 in that of 0 and 4 in that of 3. Order: 5 2 1 0 3 4. The second option is the output of BFS.
At the moment DFS goes from 4 down to 3, at which node is the temp of 1?
The answer is B. 1 called dfsVisit(2) at the node 2 in its list, and that call is not over yet. temp moves on to 4 only after 2 returns.
Show the answer
The answer is B. 1 called dfsVisit(2) at the node 2 in its list, and that call is not over yet. temp moves on to 4 only after 2 returns.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.