Showing posts with label Depth First Search Implementation in Java. Show all posts
Showing posts with label Depth First Search Implementation in Java. Show all posts

Tuesday, April 1, 2014

Depth First Search Implementation in Java


import java.util.Scanner;
import java.util.Stack;


public class DepthFirstSearch {

private Stack<Integer> stack;
public DepthFirstSearch(){
stack=new Stack<Integer>();
}
public void depthFirstSearch(int adjmtrx[][], int source){
int no_of_nodes=adjmtrx[source].length - 1;
System.out.println("no_of_nodes ++ -->"+adjmtrx[source].length);
System.out.println("no_of_nodes -->"+no_of_nodes);
int visited[]=new int[no_of_nodes+1];
int element=source;
int i=source;
System.out.print(element + "\t"+"---");
visited[source]=1;
stack.push(source);
while(!stack.isEmpty()){
element=stack.peek();
i=element;
while(i<=no_of_nodes){
if(adjmtrx[element][i]==1 && visited[i]==0){
stack.push(i);
visited[i]=1;
element=i;
i=1;
System.out.print(element + "\t" +"+++");
continue;
}
i++;
}
stack.pop();
}
}
public static void main(String[] args) {
int no_of_nodes,source;
Scanner scanner = null;
 
try{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
no_of_nodes= scanner.nextInt();
int adjmtrx[][]=new int[no_of_nodes+1][no_of_nodes+1];
System.out.println("Enter the adjacency matrix");
    for (int i = 1; i <= no_of_nodes; i++)
        for (int j = 1; j <= no_of_nodes; j++)
        adjmtrx[i][j] = scanner.nextInt();
   
    System.out.println("Enter the source for the graph");
   
            source = scanner.nextInt(); 
            System.out.println("The DFS Traversal for the graph is given by ");
            DepthFirstSearch dfs = new DepthFirstSearch();
            dfs.depthFirstSearch(adjmtrx, source);
 
}catch(Exception e){
 
}
scanner.close();
}


}