Depth-First Search Algorithm


//DFS algorithm in Java

import java.util.*;

class DFS {
private LinkedList<Integer> adjLists[];
private boolean visited[];

// Graph creation
DFS(int vertices) {
adjLists = new LinkedList[vertices];
visited = new boolean[vertices];

for (int i = 0; i <vertices; i++)
adjLists[i] = new LinkedList<Integer>();
}

// Add edges
void addEdge(int src, int dest) {
adjLists[src].add(dest);
}

// DFS algorithm
void DFS(int vertex) {
visited[vertex] = true;
System.out.print(vertex + " ");

Iterator<Integer> ite = adjLists[vertex].listIterator();
while (ite.hasNext()) {
int adj = ite.next();
if (!visited[adj])
DFS(adj);
}
}

public static void main(String args[]) {
System.out.println("Enter number of nodes for a graph");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

DFS g = new DFS(n);
int s ,d;
char c='Y';
while(c=='Y'|| c=='y')
{
	System.out.print("Enter Source node ");
	s= sc.nextInt();
	System.out.print("Enter Destination node ");
	d= sc.nextInt();
	g.addEdge(s, d);
	System.out.print("Would you like to continue(Y/N)");
	c= sc.next().charAt(0);
}
System.out.print("Enter the vertex ");
int v = sc.nextInt();

System.out.println("Following is Depth First Traversal");

g.DFS(v);
}
}