邻接矩阵上的DFS和BFS,Java
我试图用Java编写一个程序,在邻接矩阵上执行DFS和BFS。到目前为止,我已经编译了代码并给出了所需的输出 然而,我得到了一个我无法解决的错误,我觉得这可能与我的for循环有关 错误如下:邻接矩阵上的DFS和BFS,Java,java,indexoutofboundsexception,breadth-first-search,adjacency-matrix,microsoft-distributed-file-system,Java,Indexoutofboundsexception,Breadth First Search,Adjacency Matrix,Microsoft Distributed File System,我试图用Java编写一个程序,在邻接矩阵上执行DFS和BFS。到目前为止,我已经编译了代码并给出了所需的输出 然而,我得到了一个我无法解决的错误,我觉得这可能与我的for循环有关 错误如下: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at GraphMatrix.dfVisit(GraphMatrix.java:304) at GraphMatrix.dfVisi
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)
错误所在的代码如下所示:
// 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
}
最后,主要是g.DF:
}
任何帮助都将不胜感激。根据堆栈跟踪,异常是从
dfVisit()
方法引发的,显然是在计算表达式visted[u]!=已访问[v]
。从上下文来看,它必须源于u
超出访问的数组的范围(否则会在前面引发异常)。异常消息为您提供越界索引(9)的值
由于u
所取的每个值都是adj[v]
的一个元素,因此得出结论认为adj[v]
包含错误的数据似乎是合理的,否则就是您对其内容的解释不正确。我只能推测这可能是如何或为什么的,但我的第一个猜测是,adj[v]
的元素是用基于1的索引表示的(也就是说,好像最小的有效数组索引是1),而Java使用基于0的索引。因此,基于此伪代码的dfVisit方法,您有什么建议<代码>图形::dfVisit(顶点上一个,顶点v)开始访问[v]=++id打印“访问的顶点”,v,“沿边”,上一个,“-”,v用于每个顶点u 调整(v)如果未访问[u]数据访问(u)结束
我真的不能再多说了,@AmyKelly。我看不出你试图实现的算法有任何内在的错误。相反,问题似乎在于你对你正在使用的数据和/或你的实现细节的解释。你没有提供任何人需要更多的信息比我已经做的更具体。
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);
}
}
}
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);
}