简体   繁体   English

Java邻接矩阵上的DFS和BFS

[英]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. 我正在尝试用Java编写一个在邻接矩阵上执行DFS和BFS的程序。 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. 但是我遇到一个错误,无法解决,我认为这可能与我的for循环有关。

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: 然后是if语句中的第二行:

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) : 最后是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] . 根据堆栈跟踪,显然是从dfVisit()方法引发了异常,显然是在评估表达式dfVisit() visited[u] != visited[v] dfVisit() 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). 从上下文来看,它必须是由于u超出了visited数组的范围(否则会更早抛出异常)。 The exception message gives you the value of the out-of-bounds index (9). 异常消息为您提供了越界索引(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. 由于u接受的每个值都是adj[v]的元素,因此可以得出合理的结论,即adj[v]包含错误的数据,否则您将错误地解释其内容。 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. 我只能推测其可能或原因,但是我的第一个猜测是adj[v]的元素是根据基于1的索引来表示的(也就是说,最小的有效数组索引为1),而Java使用基于0的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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