# DepthFirstSearch

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);
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
```

(example here...)

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.

### References

ClassS04CS141 | recent changes | Preferences