Depth First Search (DFS) - Algorithm - Graph Traversal
"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 hashset
4. For every adjacent node of current node :
5. if current adjacent node is not in visited hashset, call dfs(current adjacent node, visited hashset) recursively.
If you want to do DFS iteratively :
1. For each node in the node list which are not visited call dfs(current node, visited hashset):
2. Add current node to stack
3. While stack is not empty:
4. pop from stack and print current node
5. Add current popped node in visited Hashset
6. for all adjacent node of current node :
7. if current adjacent node is not in visited HashSet, then add it to stack and also add it to the visited hashset .
"BFS VS DFS - When To Use Which Method ?"
- BFS is optimal for finding the shortest distance as compared to DFS. To explain this let's take an example of a graph: In the above graph, suppose we want to find the shortest distance between node 1 and 3 and 1 being the start node. Suppose we use DFS. We start from node1 and suppose we go to node 2 first. By doing that you can see we follow this path: 1->2->4->6->5->3. Node 3 is found very late. But if we use BFS in this case, we follow the path : 1->2->3. Clearly, BFS wins the game of finding the shortest distance quickly than DFS.
Comments
Post a Comment