【发布时间】:2017-03-21 20:11:14
【问题描述】:
我正在尝试用 Java 编写一个在邻接矩阵上执行 DFS 和 BFS 的程序。到目前为止,我的代码可以编译并提供所需的输出。
但是我遇到了一个我无法解决的错误,我觉得这可能与我的 for 循环有关。
错误如下:
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)
出错的代码如下sn-ps:
// 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
}
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);
}
}
}
最后是 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);
}
}
任何帮助将不胜感激。
【问题讨论】:
标签: java indexoutofboundsexception breadth-first-search adjacency-matrix microsoft-distributed-file-system