java.lang.stackoverflowerror在DFS中迭代



我当前正在尝试通过我自己创建图形类代表游戏的图表。构造函数是这个(希望我在这里没有任何逻辑错误(:

 private int nNodes; 
    private int nEdges;
    private List<Integer> adj[];
    private boolean visited[];
    public GameGraph()
    {
        nNodes = 81;
        adj = new LinkedList[nNodes];
        for(int i = 0; i < nNodes; i++)
            adj[i] = new LinkedList();
        visited = new boolean[nNodes];
    }

我使用深度第一个搜索算法检查源和目标之间是否有路径。这就是我写的:

 public boolean hasPath(int source , int dest)
        {
            if(source >= nNodes)
                return false;
            else
            {
                visited[source] = true;
                try
                {
                    Iterator<Integer> iterator = adj[source].listIterator();
                    while(iterator.hasNext())
                    {
                        int n = iterator.next();
                        if(n == dest)
                            return true;
                        visited[n] = true;
                        if(hasPath(n, dest))
                            return true;
                    }//end while
                    return false;
                }//end try
                catch(NullPointerException exception)
                {
                    exception.printStackTrace();
                }//end catch
                return false;
            }//end else
        }//end method has path

问题是,当我在主类中运行此方法时,我有此错误:

Exception in thread "main" java.lang.StackOverflowError
    at java.util.LinkedList$ListItr.<init>(Unknown Source)
    at java.util.LinkedList.listIterator(Unknown Source)
    at java.util.AbstractList.listIterator(Unknown Source)
    at java.util.AbstractSequentialList.iterator(Unknown Source)
    at logic.GameGraph.hasPath(GameGraph.java:67)
    at logic.GameGraph.hasPath(GameGraph.java:74)at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)
    at logic.GameGraph.hasPath(GameGraph.java:74)

第67行是:

   Iterator<Integer> iterator = adj[source].listIterator();

和第74行是递归电话:

if(hasPath(n, dest))

我读到了有关StackoverFlowerRor的信息,这与缺乏可用的记忆有关,我知道一个和我的问题不是那样。但是我不明白为什么在这里应该发生迭代器的原因。即使是使用彼此接近的节点,我也尝试了它,这些节点只有几个递归调用,并且发生了相同的错误。

进入递归呼叫之前检查是否已经使用

介绍了该节点
....
int n = iterator.next();
if(!visited[n]){
...
}

最新更新