Click here to Skip to main content
14,694,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
output :

Enter Vertex no : 
How many edge you want to enter : 
Enter edge : 0 1
Enter edge : 0 2
Enter edge : 1 3
Final Visited Order : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at DFS.DFS_Visit(
	at DFS.traverse(
	at DFS.main(

What I have tried:

//My code --

import java.util.*;

public class DFS {
	static int ver;
	static int edg;
	static int time;
	static int u;
	static int source;
	static int destination;
	static final int white=0,grey=1,black=2;
	static int prev[]=new int[ver];
	static int color[]=new int[ver];
	static int d[]=new int[ver];
	static int f[]=new int[ver];
	int vertex[]=new int[ver];
	static LinkedList<integer>list[];
	   @SuppressWarnings({ "unchecked", "static-access" })
public DFS(int ver) {
	   this.ver = ver;
	   list = new LinkedList[ver];
	   for (int i = 0; i <ver; i++)="" {
="" list[i]="new" linkedlist<="">();
	public void addEdge(int source,int destination) {
	public void traverse(){
		 int prev[]=new int[ver];
		 int color[]=new int[ver];
		 int d[]=new int[ver];
		 int f[]=new int[ver];
		 int time;
		for(u=0;u<ver;u++) {
="" color[u]="white;
" prev[u]="-1;
" f[u]="Integer.MAX_VALUE;
" d[u]="Integer.MAX_VALUE;
" }
="" time="0;
="" for(u="0;u<ver;u++)" if(color[u]="=white)
" dfs_visit(u);
="" public="" void="" dfs_visit(int="" u)="" iterator<integer="">ver=list[u].listIterator();
		while(ver.hasNext()) {
			if(color[v]==white) {
		System.out.println(u+" ");
	public static void main(String[] args) {
		System.out.println("Enter Vertex no : ");
		Scanner in1=new Scanner(;
		System.out.println("How many edge you want to enter : ");
		Scanner number=new Scanner(;
		DFS graph=new DFS(ver);
		for(int e=0;e
Updated 7-Jul-20 22:35pm
Richard MacCutchan 8-Jul-20 3:39am
Don't declare the fields in your class as static, you will get totally wrong answers if you create multiple DFS objects.

1 solution


you may have noticed not all of your code is showing, it stopped at some < sign, the rest was discarded as unexpected HTML code, because you did not enclode everything with PRE tags (that is what the code widget is for, or the "paste as code block" dialog).

The clue usually is in the error message you are getting "Index 0 out of bounds for length 0"; you do not really want a zero-length array, do you?
I see
static int ver;
static int prev[]=new int[ver];

Now static code such as the initialization of prev[] gets executed at once when the class is referenced for the first time, and ver is still zero at that time. You'll have to reorganize things a bit...


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900