I am trying to write a program in Java which performs DFS and BFS on an adjacency matrix. The code I have so far compiles and gives the desired output so far.
However I am getting an error which I am unable to resolve which I feel may have something to do with my for loops.
The error is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at GraphMatrix.dfVisit(GraphMatrix.java:304)
at GraphMatrix.dfVisit(GraphMatrix.java:306)
at GraphMatrix.dfVisit(GraphMatrix.java:306)
at GraphMatrix.DF(GraphMatrix.java:261)
at GraphMatrix.main(GraphMatrix.java:347)
The code where the errors are the below snippets:
// method to initialise Depth First Traversal of Graph
public void DF( int s)
{
id = 0;
for(int v = 1; v <= V; v++) {
visited[v] = 0;
}
dfVisit(0, s); //error being signaled here
}
And the second on the lines from the if statment:
private void dfVisit( int prev, int v)
{
visited[v] = ++id;
System.out.println("Visited vertex" + ": " + v + " Along edge : " + prev);
for (int u: adj[v]) {
if (visited[u] != visited[v]) {
dfVisit(prev, u);
}
}
}
And finally in the main, the g.DF(s) :
public static void main(String[] args) throws IOException
{
int s = 4;
String fname = "wGraph3.txt";
GraphMatrix g = new GraphMatrix(fname);
g.display();
g.DF(s);
g.BF(s);
}
}
Any help would be appreciated.