Depth first search, or DFS is a core algorithm used to traverse trees and graphs. Much like BFS, it starts at an arbitrary node and explores the graph until it finds a spanning tree. The main difference is that instead of using a working queue to store nodes to visit, depth first search will instead usually use a stack.

Implementation

An example implementation of depth first search could look something like the following:

typdef enum {VISITED, NEW} state;
 
void DFS(Graph G, Node* n){
	Stack s;
	s.push(n);
	n->state = state.VISITED;
	
	while(!s.isEmpty()){
		Node* currentNode = s.pop();
		
		if(currentNode->state != state.VISITED){
			currentNode->state = state.VISITED;
			
			for(Node* adjNode : G.getAdjacentNodes(currentNode)){
				s.push(adjNode);
			}
			
		}
	}
}

It is quite simple in its implementation. There is also a recursive implementation that is quite similar.

Example

Try tracing the following graph implemented with an adjacency list with DFS starting at node A.

Time Complexity

The time complexity of using depth-first search using an adjacency matrix is

But when maximally efficient using an adjacency list, the time complexity is:

Where V and E are the number of vertices and edges respectively.