Tuesday, February 7, 2017

Breadth first Traversal(BFT) AND Depth First Traversal(DST) Program in java

Hello Guys , Hope you all are doing good , so today we are going to see the BST and DST Program in java.

Let see the implementation of BST and DST in single program


package inv.learning.searching;

import java.util.Iterator;
import java.util.LinkedList;

public class BFT {

public static void main(String[] args) {

Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 4);
System.out.println("Breadth First Search --");
g.BST(0);

System.out.println("Depth first search --");
g.DST(0);

}
}
class Graph{

int V;
LinkedList adj[];

Graph(int v){
V=v;
adj = new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]= new LinkedList<>();
}
}
public void addEdge(int v,int w)
{
adj[v].add(w);
}

public void BST(int s)
{
boolean[] visited = new boolean[V];
visited[s]=true;
LinkedList<Integer> queue= new LinkedList<>();
queue.add(s);
while(queue.size()!=0)
{
int n = queue.poll();
System.out.println(n+" ");
Iterator<Integer> itr = adj[n].listIterator();
while(itr.hasNext())
{
int i = itr.next();
if(!visited[i]){
visited[i]=true;
queue.add(i);
}

}
}

}
public void DST(int s){
boolean[]  visited = new boolean[V];

DSTUtil(s, visited);
}

public void DSTUtil(int s, boolean[] visited){
visited[s]=true;
System.out.println(s+" ");
Iterator itr = adj[s].listIterator();
while(itr.hasNext())
{
int i = (int) itr.next();
if(!visited[i])
{
DSTUtil(i, visited);

}
}


}


}

Output-

Breadth First Search --


Depth first search --


Thanks for reading
-Noeik

0 comments:

Post a Comment