【问题标题】:I am trying to do BFS search but get Runtime Error Index out Of Bounds Exception我正在尝试进行 BFS 搜索,但运行时错误索引超出范围异常
【发布时间】:2021-05-04 16:23:58
【问题描述】:

给定一个有向图,任务是从0开始对该图进行广度优先遍历。

完成函数bfsOfGraph()以返回给定图的广度优先遍历。

这里,V 表示顶点数。

这就是问题link

class Solution
{    
         public ArrayList<Integer> bfsOfGraph(int V , ArrayList<ArrayList<Integer>> adj)
         {    
                  ArrayList<Integer> bfs = new ArrayList<>();
                  boolean vis[] = new boolean[V+1]; 
        
                 for( int i = 1; i < V+1 ; i++){
                         if(vis[i] == false){
                             Queue<Integer> q = new LinkedList<>();
                             q.add(i);
                             vis[i] = true;
                
                             while(!q.isEmpty()){
                                 
                                     Integer node = q.poll();
                   
                                     bfs.add(node);
                 
                                    for(Integer it : adj.get(node)){
                                            if(vis[it] == false){
                                            vis[it] = true;
                                            q.add(it);
                                   }
                            }   
                      }
                }
          }
        return bfs;
        
    }
}

【问题讨论】:

    标签: java graph indexoutofboundsexception breadth-first-search


    【解决方案1】:

    当您知道您已经从 0 开始(图的原点)时,为什么要调用图的每个节点(顶点)。我认为你误解了这些问题。您必须在 Origin 0 上应用 BFS。您也可能会得到 IndexOutOfBound 异常,因为图形的所有顶点都是从 0 到 V-1(含)。我可以看到您将图形顶点视为 1 到 V 包括在内。

    public ArrayList<Integer> bfsOfGraph(int V,ArrayList<ArrayList<Integer>> adj)
        {
            Queue<Integer> queue = new LinkedList<>();
            boolean visited[] = new boolean[V];
            ArrayList<Integer> results = new ArrayList<>();
            queue.add(0);
            while(!queue.isEmpty()){
                Integer nextNode = queue.poll();
                results.add(nextNode);
                visited[nextNode] = true;
                if(adj.get(nextNode) != null){
                    for(int neighbor : adj.get(nextNode)){
                        if(!visited[neighbor]){
                            queue.add(neighbor);
                            visited[neighbor] = true;
                        }
                    }
                }
            }
            return results;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2017-01-26
      • 1970-01-01
      • 2017-05-12
      • 2011-03-16
      相关资源
      最近更新 更多