简体   繁体   中英

DFS and BFS on Adjacency Matrix, Java

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.

According to the stack trace, the exception is thrown from the dfVisit() method, apparently when evaluating the expression visited[u] != visited[v] . From context, it must arise from u being out of bounds for array visited (else an exception would have been thrown earlier). The exception message gives you the value of the out-of-bounds index (9).

Since each value u takes is an element of adj[v] , it seems reasonable to conclude that adj[v] contains bad data, or else that you are interpreting its contents incorrectly. I can only speculate about how or why that may be, but my first guess would be that the elements of adj[v] are expressed in terms of 1-based indexing (that is, as if the smallest valid array index were 1), whereas Java uses 0-based indexing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM