This is the Depth of the first search written iteratively , not recursively.
The recursive DFS pseudocode (preorder) is as follows:
visit (current node) for each child node of current node if node is not explored dfs (node)
An iterative version of DFS looks like this:
Put current node on stack In a while loop pop the stack if not empty visit (popped node) push all Unvisited and NotVisiting neighbors of popped node on the stack End while
Invisible and notVisiting in the iterative version means that the node is not visited before, nor is it on the stack for visiting.
the time complexity of this algorithm depends on whether the graph was saved as an adjacency list or adjacency matrix. For the list, this will be O (n). For a matrix, this will be O (n 2 ), because although you examine each node only once, you need to visit each row and column of the matrix to find out if there is a path between a node X and node Y.
the complexity of the space of this algorithm can go to the worst of O (n), when the graph will have node only one neighbor, becoming like one list. p>
source share