2. DFSALGORITHM
• Depth-first search (DFS) is an algorithm for traversing or searching tree or
graph data structures. The algorithm starts at the root node and explores
as far as possible along each branch before backtracking.
• DFS will continue to visit neighbors in a recursive pattern
• Whenever we visit v from u, we recursively visit all unvisited neighbors of v.
• Then we backtrack (return) to u. u
v
w1 w2
w3
2
3. CONTINUE… DFS ALGORITHM
The purpose of the algorithm is to mark each vertex as visited while
avoiding cycles.
The DFS algorithm works as follows:
• Start by putting any one of the graph's vertices on top of a stack.
• Take the top item of the stack and add it to the visited list.
• Create a list of that vertex's adjacent nodes. Add the ones which aren't
in the visited list to the top of stack.
• Keep repeating steps 2 and 3 until the stack is empty.
3
17. EXAMPLE
Result:
The printing sequence of the graph will be :
0 1 7 2 3 4 8 5 6
Final Path
• All nodes are covered by DFS Algorithm
17