"What is Depth First Search (DFS)" DFS is an algorithm for traversing the Graph Data Structure. We can start from a node and go to one of its neighbours and then its neighbour and so on. After this, we come to the other neighbour of the start node and check its neighbour and so on. Basically, we are traversing in depth. It is similar to the Depth First Traversal of a tree, but unlike a tree, a graph may contain cycles, so we need to keep track of visited nodes too in order to ensure we do not traverse the already traversed node and thus avoid getting stuck in the cycle or loop forever. Algorithm for DFS : [Time Complexity: O(V+E) , Space Complexity: O(V+E)] If you want to do DFS recursively : 1. For each node in the node list which are not visited call dfs(current node, visited hashset): 2. If current node is present in visited hashset return 3. Else Print current node and add current node to visited h...
Comments
Post a Comment