# Cs141 Home/Lecture9

Cs141 Home | Cs141 Home | recent changes | Preferences

### Depth-first search (DFS)

Depth-first search is a "backtracking" method of exploring a graph. It searches from vertex to vertex, backtracking when it encounters vertices that have already been discovered. Here is pseudo-code:

```DFS(graph G)
Array<int> visited(0);
For each vertex v in G:
DFS1(G, v, visited);
end

DFS1(graph G, vertex v, Array<int>& visited)
if (visited[v] == 1)  return
visited[v] = 1
for each neighbor w of v do
DFS1(G, w, visited)
end
```

DFS on an undirected graph classifies the edges into two kinds:

• DFS tree edges -- these are the edges (v,w) such that DFS1(G, w, visited) is called directly from within DFS1(G, v, visited) when w is not yet visited. The tree
edges form the DFS tree (or if the graph is not connected, a forest) rooted at the start vertex.
• back edges -- these are the edges (v,w) such that DFS1(G, w, visited) is called directly from within DFS1(G, v, visited), where w is an ancestor of v in the DFS tree.

The tree edges form a tree (essentially a recursion digram for the DFS). For any back edge (u,v), either u is a descendant of v in this tree or vice versa.

Note that there are no "cross" edges (edges (u,w) where u is neither a descendant nor an ancestor of v in the DFS tree). Later we will see that if the graph is directed, the DFS can yield cross edges.

In a graph with N vertices and M edges, the running time for DFS is O(N+M), because the work done for each vertex is proportional to the degree of the vertex, and the sum of the vertex degrees is 2M.

Essential facts about DFS in undirected graphs:

1. The DFS classifies every edge in the graph as a tree edge or back edge.
2. (u,w) is a tree edge if the call DFS1(G, u, visited) recursively calls DFS1(G, w, visited) when visited[w]=0.
3. every other edge is a back edge.
4. The tree edges contain no cycles.
5. The tree edges connect all connected pairs of vertices. That is, if there is a path in the graph from u to w, then there will be a path along the tree edges.

Exercises:

1. G has a cycle iff any DFS of G classifies some edge as a back edge.
2. G has at least two distinct cycles iff any DFS of G produces at least two back edges.
3. Is it the case that G has at least three distinct cycles iff any DFS produces at least three back edges?

References:
Chapter 12 of Goodrich, Mount, Tomassia.

Cs141 Home | Cs141 Home | recent changes | Preferences