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
DFS on an undirected graph classifies the edges into two kinds:
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.