Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, July 26, 2017

DFS Graph


Problem ;

Print Depth first traversal of graph

Solution:

It is similar to tree except it may have cycle so we need to check whether node has been already visited.

Set iterator through linked list having details of connected vertices and check if it is  not visited then recur and print , do till all nodes are visited


Code;

  public void DFS(int v,LinkedList<Integer> adj[],boolean visited[])
    {
      visited[v]=true;
          System.out.print(v+" ");
      Iterator<Integer> itr=adj[v].iterator();
      while(itr.hasNext())
      {
          int item=itr.next();
          if(!visited[item])
          {
          DFS(item,adj,visited);
          }
      }
    }

0 Comments:

Post a Comment

Stats