Posts

Showing posts with the label DFS

Graph Traversal Code - DFS on Graph represented using Adjacency List

Image
  import java.util.*; // A graph node  class GraphNode{     String name;     // this is a list of adjacent nodes for the current node and is  used in adjacency list     ArrayList<GraphNode> neighbours;          // constructor     GraphNode(String name){         this.name = name;         this.neighbours = new ArrayList<>();     } } public class Main {     // The node list of graph , also used to maintain adjacency list     ArrayList<GraphNode> nodeList;          // constructor     Main(){         this.nodeList = new ArrayList<>();     }            // function to add an undirected and unweighted edge between two nodes with index i and j in nodeList     public void addUndirectedEdge(int i, int j){     ...

Depth First Search (DFS) - Algorithm - Graph Traversal

Image
"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...