Depth-First Search (DFS) is a fundamental graph traversal algorithm used to explore or search through a graph. It starts at a given vertex and explores as far as possible along each branch before backtracking. It has various applications. For example, it can be used to detect cycles or find connected components.
The DFS algorithm can be implemented using a stack or recursion. Here is a basic outline of the algorithm:
A stack is a data structure that follows the principle of "last-in, first-out" (LIFO), where elements are added to the top and removed from the top.
In this section, we will push neighbors in reverse order, e.g. from big to small. So that the smaller neighbors will be visited first.
Click on Auto Play to see the algorithm in action.
Node ID:
Traversal Order: 0
0
➜
1
➜
3
➜
5
➜
6
➜
7
➜
4
➜
2
➜
8
➜
9
0-1
➜
1-3
➜
3-5
➜
5-6
➜
3-7
➜
1-4
➜
0-2
➜
2-8
➜
2-9