Depth First Search (DFS) AlgorithmDepth first search (DFS) algorithm starts with the initial node of the graph G, and then goes to deeper and deeper until we find the goal node or the node which has no children. The algorithm, then backtracks from the dead end towards the most recent node that is yet to be completely unexplored. The data structure which is being used in DFS is stack. The process is similar to BFS algorithm. In DFS, the edges that leads to an unvisited node are called discovery edges while the edges that leads to an already visited node are called block edges. Algorithm
Example :Consider the graph G along with its adjacency list, given in the figure below. Calculate the order to print all the nodes of the graph starting from node H, by using depth first search (DFS) algorithm. Solution :Push H onto the stack POP the top element of the stack i.e. H, print it and push all the neighbours of H onto the stack that are is ready state. Pop the top element of the stack i.e. A, print it and push all the neighbours of A onto the stack that are in ready state. Pop the top element of the stack i.e. D, print it and push all the neighbours of D onto the stack that are in ready state. Pop the top element of the stack i.e. F, print it and push all the neighbours of F onto the stack that are in ready state. Pop the top of the stack i.e. B and push all the neighbours Pop the top of the stack i.e. C and push all the neighbours. Pop the top of the stack i.e. G and push all its neighbours. Pop the top of the stack i.e. E and push all its neighbours. Hence, the stack now becomes empty and all the nodes of the graph have been traversed. The printing sequence of the graph will be :
Next TopicSpanning Tree
