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);
}
}
}
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