algoritmauzmanı
Sign in
TREN
8.2Graph with Adjacency Lists
Lesson 8.2.5

Depth-first search (DFS)

This lesson is the twin of DFS with a matrix. 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 , not by scanning a row. That way each call looks only at the edges of its own vertex.

What you will learn
  • 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
8 minTime O(n + e)Memory O(n)C · Java · Python

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 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 matrixDFS with lists
NeighboursThe n cells of the row are scannedThe d nodes of the list are walked
Work per callO(n)O(d)
Total timeO(n²)O(n + e)
Checked in the sample36 cells14 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.

adjNULLNULLNULLNULLNULLNULL012345012345?0?1?2?3?4?51?3?0?2?4?1?5?0?4?1?3?5?2?4?u
Call stack
  1. Start: no vertex is marked. dfs(&g, 0) is called.
  2. dfsVisit(0): 0 is marked and printed. The walk of the list of 0 begins. Output: 0.
  3. The first node in the list of 0 is 1, unmarked. While the temp of 0 waits at this node, dfsVisit(1) is called. Output: 0 1.
  4. The list of 1 is 0, 2, 4. 0 is marked; at 2, dfsVisit(2) is called. Output: 0 1 2.
  5. The list of 2 is 1, 5. 1 is marked; DFS goes down to 5. Output: 0 1 2 5.
  6. The list of 5 is 2, 4. 2 is marked; DFS goes down to 4. Output: 0 1 2 5 4.
  7. 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.
  8. The 0 and 4 in the list of 3 are marked: 3 returns. The temp of 4 moves to 5, which is marked: 4 returns. 5 and 2 return as well. The temp of 1 moves from 2 to 4; 4 is marked.
  9. 1 returns. The temp of 0 moves from 1 to 3: 3 is marked. 0 returns too and the stack is empty.
  10. 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

Time
O(n + e)

One call per vertex (n); each call walks its list once, and the lists add up to 2e nodes.

Memory
O(n)

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 ; 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?

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?

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.