###Depth First Search [DFS] - A Graph traversal algorithm
Starting from root, this algorithm goes on exploring every node in a preorder traversal pattern.
Although it closely resembles with preorder traversal, there is a slight difference. Each nodes are visited only once. It goes on exploring till the leaves appear and then backtrace to neighbour and then again other siblings. It keeps a record of whether a node has been visited or not. Since it's operation is highly stack dependent, the most easy way to achieve this is by recursion.
DFS(Vertex V):
Mark V as VISITED
FOR EACH neighbour U of V:
IF U NOT VISITED:
DFS(U)
END IF
END FOR
END DFS
The complexity of DFS Traversal runs in the order of
O(|V| + |E|)
, where|V|
and|E|
represents the number of vertices and edges in the graph. It wraps up in a space complexity ofO(|V|)
at max.