Depth first search goes as deep as possible before backing up. It is the basis of many graph algorithms.

The Algorithm

Depth first search (DFS) from a vertex u marks u visited and then, for each neighbour v of u, if v is unvisited, recursively performs DFS from v. When all neighbours are done the search backtracks. It uses a stack, either the recursion stack or an explicit one. For a whole graph, DFS is restarted from every unvisited vertex, so it covers disconnected graphs too. The time is Θ(V + E) with adjacency lists and Θ(V²) with a matrix; the space is Θ(V) for the stack and marks.

Discovery and Finish Times

Many uses need two time stamps per vertex: discovery time d[u] when it is first visited and finish time f[u] when its neighbours are all processed. The intervals [d, f] of two vertices are either nested or disjoint, which reveals the structure of the graph. DFS builds a DFS tree (or forest) and classifies edges as tree edges, back edges, forward edges and cross edges; an undirected graph has only tree and back edges, and a back edge shows a cycle.

Connected Components

A connected component of an undirected graph is a maximal set of vertices in which every two are joined by a path. To find them, run DFS (or BFS) from an unvisited vertex; everything visited in that run forms one component; then start again from another unvisited vertex, and count the runs. The total time is Θ(V + E). Applications: finding islands in an image, detecting disconnected networks, grouping friends in a social graph and checking whether a graph is connected (one component).

Definition: Connected component. A maximal subset of vertices of an undirected graph such that there is a path between every pair of its vertices.

Table 3.6: BFS versus DFS

Basis BFS DFS
Structure Queue Stack or recursion
Order Level by level Deep first, then backtrack
Time Θ(V + E) Θ(V + E)
Typical uses Shortest unweighted paths Components, cycles, ordering

Example 3.6: Finding connected components

Problem: Vertices A to H with edges A-B, A-C, B-D, C-D, E-F, F-G (H has no edge). Find the components and the DFS order from A.

Solution:

  1. DFS from A (alphabetical): A, then B, then D (from B), then C (from D); back at A all done. Order A, B, D, C.
  2. Next unvisited vertex E: DFS gives E, F, G.
  3. Next unvisited vertex H: only H.

Result: Three components {A, B, C, D}, {E, F, G} and {H}.

g = {"A": "BC", "B": "AD", "C": "AD", "D": "BC",
     "E": "F", "F": "EG", "G": "F", "H": ""}
seen, comps = set(), []
def dfs(u, out):
    seen.add(u)
    out.append(u)
    for v in g[u]:
        if v not in seen:
            dfs(v, out)
for s in sorted(g):
    if s not in seen:
        out = []
        dfs(s, out)
        comps.append(out)
print(comps)
print("number of components:", len(comps))

Output

[['A', 'B', 'D', 'C'], ['E', 'F', 'G'], ['H']]
number of components: 3

Common mistakes

  • Using DFS from a single vertex and calling the result the whole graph's components.
  • Forgetting the visited array and looping forever on a cycle.
  • Treating DFS order as unique; it depends on neighbour order.
  • Assuming a back edge in an undirected graph is the edge to the parent.

Key takeaways

  • DFS goes deep, then backtracks, using a stack or recursion.
  • Time Θ(V + E) with adjacency lists.
  • Components: restart the search from each unvisited vertex.
  • A back edge in an undirected graph reveals a cycle.

Practice questions

  1. How are connected components found with DFS?
  2. What is the time complexity of DFS with adjacency lists?
  3. What does a back edge indicate in an undirected graph?

Answers to the practice questions

  1. Run DFS from each unvisited vertex; each run visits one component.
  2. Θ(V + E).
  3. A cycle.

Sources

  • Official BCA syllabus Design and Analysis of Algorithms, course code 26BCA404DS03, Unit III