簡體   English   中英

廣度優先搜索錯誤

[英]breadth first search error

有向圖 矩陣

public int bfs(int maxDepth){ //maxDepth = 3 works.. maxDepth = 4 gives me an error
        int src = 0;
        int dest = 2;
        int nodes = arr[src].length - 1;
        boolean[] visited = new boolean[nodes + 1];
        int i;
        int countDepth = 0;
        int countPaths = 0;
        int element;


        queue.add(src);

        while(!queue.isEmpty() || countDepth != maxDepth)
        {
            element = queue.remove();
            i = element;

            while(i <= nodes)
            {
                if(arr[element][i] > 0 && visited[i] == false)
                {
                    queue.add(i);
                    visited[i] = true;

                    if(arr[i][element] > 0) //if it has two directions
                        visited[i] = false;

                    if(element ==  dest || i == dest)
                        countPaths++;
                }

                i++;
            }

            countDepth++;
        }

        return countPaths;
    }

我在嘗試計算到達目的地的路徑數時,嘗試增加“ x”級的水平。

由於某些原因,我不斷收到錯誤消息:

Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.removeFirst(Unknown Source)
at java.util.LinkedList.remove(Unknown Source)
at Graph.bfs(Graph.java:48)

我不明白發生了什么。 當我深入3個級別時,它似乎起作用,但是當我將其更改為4級時,它不起作用。

更改

while(!queue.isEmpty() || countDepth != maxDepth)

while(!queue.isEmpty() && countDepth != maxDepth)

每個圖都有一些最大深度。 看來,您將maxDepth設置為大於給定圖形的實際可能值,即使處理了所有可能的節點(例如,當隊列為空時),循環也會嘗試繼續bfsing

更新我將嘗試為您在評論中發布的第二個問題提供答案,即使給定的信息實際上還不夠,因此,我將盡力做到Extrasens =)我想,您將計算length=1所有路徑length=2.. length=givenMaxDepth|maxPossibleDepth 我看到了queue數據結構,但沒有看到聲明- 您是否對所有函數調用使用相同的隊列? 如果是,則應在每次調用后清除隊列 (調用queue.clear()最佳位置是在return語句之前)。

另外,我看到您在每個調用中都使用了新的訪問數組,這是正確的,但是如果您實際上使用了一些全局訪問,則還應在每次調用后“清除”已訪問的數組,換句話說,將其填充為false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM