algoritmauzmanı
Sign in
TREN
8.1Graph with an Adjacency Matrix
Lesson 8.1.5

Depth-first search (DFS)

walks a graph layer by layer, spreading out. (DFS) walks it like a maze: it follows the first path it finds as deep as it can, goes back to the previous vertex at a dead end and turns from there onto a path not yet tried. gives this going back for free.

What you will learn
  • How DFS goes deep from a vertex and how it comes back
  • Why the call stack of the recursion is the stack of DFS
  • Why DFS and BFS give different orders on the same graph
8 minTime O(n²)Memory O(n)C · Java · Python

1The idea

dfs(g, start) sets up a visited array and calls dfsVisit with the start vertex. dfsVisit(g, u, visited) first marks u and prints it. Then it walks the row of u; when it finds the first unmarked neighbour it calls itself for it at once. The other neighbours of u wait until that call is over.

If all neighbours of a vertex are marked, the loop ends and the function returns; that is a dead end. The calling vertex goes on scanning its row from where it stopped. This going back (backtracking) needs no extra structure: the remembers which vertex you were on and where in its row. You can also replace the recursion with an explicit ; a stack takes the place of the queue in BFS.

In the example BFS printed 1 and 3, at distance 1, right after 0. DFS goes from 0 down to 1, then 2, 5 and 4, and reaches 3 last: 0 1 2 5 4 3. Although 3 is a neighbour of 0, it is found through 4 before its turn comes in the row of 0.

BFSDFS
Helper structureQueueStack (the call stack)
OrderLayer by layerDeep first
Sample output (from 0)0 1 3 2 4 50 1 2 5 4 3
Typical usePath with the fewest edgesCycle detection, topological sort

In a tree, preorder is a DFS: the root is printed, then you go down into the left subtree. A tree has no cycles, so no visited array is needed; a graph needs one.

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 (orange), the green ones were printed earlier. The orange edge is the one used to go down to a new vertex. The call stack is shown under the drawing, the newest call last.

012345012345012345?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01?01u
Call stack
  1. Start: no vertex is marked. dfs(&g, 0) is called.
  2. dfsVisit(0): 0 is marked and printed. The scan of row 0 begins. Output: 0.
  3. The first unmarked neighbour in row 0 is 1. dfsVisit(1) is called at once: 1 is printed. Output: 0 1.
  4. In row 1, 0 is marked; next is 2. dfsVisit(2): 2 is printed. Output: 0 1 2.
  5. In row 2, 1 is marked; next is 5. dfsVisit(5). Output: 0 1 2 5.
  6. In row 5, 2 is marked; next is 4. dfsVisit(4). Output: 0 1 2 5 4.
  7. In row 4, 1 is marked; next is 3. dfsVisit(3). Output: 0 1 2 5 4 3. Every vertex is printed, but the calls are not over yet.
  8. The neighbours of 3, 0 and 4, are marked: 3 returns. The last neighbour of 4, 5, is marked: 4 returns. 5 and 2 return as well. Control is back in 1, which goes on with its row at column 4; 4 is marked.
  9. 1 returns. 0 goes on with its row from where it stopped: 3 is marked. 0 returns too and the stack is empty.
  10. DFS order: 0 1 2 5 4 3. The orange edges formed a DFS tree: one long branch.

#define MAX 8 struct Graph {    int n;    bool directed;    int adj[MAX][MAX];}; void dfsVisit(struct Graph* g, int u, bool visited[]) {    visited[u] = true;    printf("%d ", u);    for (int v = 0; v < g->n; v++)        if (g->adj[u][v] == 1 && !visited[v])            dfsVisit(g, v, visited);        // dive into the neighbour} void dfs(struct Graph* g, int start) {    bool visited[MAX] = {false};    dfsVisit(g, start, visited);}
class MatrixGraph {    int n;    boolean directed;    int[][] adj;     MatrixGraph(int n, boolean directed) {        this.n = n;        this.directed = directed;        adj = new int[n][n];    }     void dfsVisit(int u, boolean[] visited) {        visited[u] = true;        System.out.print(u + " ");        for (int v = 0; v < n; v++)            if (adj[u][v] == 1 && !visited[v])                dfsVisit(v, visited);       // dive into the neighbour    }     void dfs(int start) {        boolean[] visited = new boolean[n];        dfsVisit(start, visited);    }}
class MatrixGraph:    def __init__(self, n, directed=False):        self.n = n        self.directed = directed        self.adj = [[0] * n for _ in range(n)]     def dfs_visit(self, u, visited):        visited[u] = True        print(u, end=" ")        for v in range(self.n):            if self.adj[u][v] == 1 and not visited[v]:                self.dfs_visit(v, visited)      # dive into the neighbour     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²)

dfsVisit is called once for each vertex and walks the n cells of its row: n × n.

Memory
O(n)

The visited array holds n elements. In the worst case the call stack goes n calls deep.

In a very large graph the recursion can go deeper than the stack allows (Python's default limit is 1000 calls). Then DFS is written as a loop with an explicit stack. DFS with adjacency lists takes O(n + e).

4Common mistake

A common mistake is creating the visited array inside the recursive function:

void dfsVisit(struct Graph* g, int u) {    bool visited[MAX] = {false};    // wrong: a new array in every call    visited[u] = true;    ...

Every call starts with its own empty array and cannot see the marks of the previous call. You go from 0 down to 1, in 1's array 0 looks unmarked, and you go down to 0 again: endless recursion and finally a stack overflow. The visited array is created once, in dfs, and the same array is passed to every call.

5Try it

If DFS starts at vertex 3 of the sample graph, what is the output?

Show the answer

The answer is B. The first neighbour of 3 is 0, the first unmarked neighbour of 0 is 1, then 2 for 1, 5 for 2 and 4 for 5. Order: 3 0 1 2 5 4. The first option is the output of BFS.

In recursive DFS, what keeps the vertex to go back to?

Show the answer

The answer is C. Each call keeps its vertex and its place in the row in its own frame. When a call ends, the calling frame goes on from where it stopped.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.