ClassS04CS141 | 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, vertex v)
   Array<int> visited(0);
   DFS1(G, v, visited);

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)

(example here...)

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

edges form the DFS tree (or if the graph is not connected, a forest) rooted at the start vertex.

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.


ClassS04CS141 | recent changes | Preferences
This page is read-only | View other revisions
Last edited May 4, 2004 8:00 pm by Neal (diff)