Java 我正在尝试执行BFS搜索,但获取运行时错误索引超出范围异常

Java 我正在尝试执行BFS搜索,但获取运行时错误索引超出范围异常,java,graph,indexoutofboundsexception,breadth-first-search,Java,Graph,Indexoutofboundsexception,Breadth First Search,给定一个有向图,任务是从0开始对该图进行广度优先遍历 完成函数bfsOfGraph(),返回给定图形的宽度优先遍历 这里,V表示顶点的数量 问题出在这里 类解决方案 { 公共阵列列表bfsOfGraph(int V,阵列列表adj) { ArrayList bfs=新的ArrayList(); 布尔vis[]=新布尔[V+1]; 对于(int i=1;i

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

完成函数
bfsOfGraph()
,返回给定图形的宽度优先遍历

这里,
V
表示顶点的数量

问题出在这里

类解决方案
{    
公共阵列列表bfsOfGraph(int V,阵列列表adj)
{    
ArrayList bfs=新的ArrayList();
布尔vis[]=新布尔[V+1];
对于(int i=1;i
当您知道已从0开始(图形的原点)时,为什么要调用图形的每个节点(顶点)。我想你误解了这些问题。您必须在原点0上应用BFS。您可能也会得到IndexAutofBound异常,因为图的所有顶点都是从0到V-1(包括0到V-1)。我可以看到你把图的顶点视为1到V(包括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;
    }
public数组列表bfsOfGraph(intv,数组列表adj)
{
Queue Queue=new LinkedList();
布尔值[]=新布尔值[V];
ArrayList结果=新建ArrayList();
添加(0);
而(!queue.isEmpty()){
整数nextNode=queue.poll();
结果。添加(下一个节点);
已访问[nextNode]=真;
if(调整获取(下一个节点)!=null){
for(int邻居:调整get(nextNode)){
如果(!访问[邻居]){
添加(邻居);
拜访[邻居]=真实;
}
}
}
}
返回结果;
}
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;
    }