问题描述
给定一个有向图,任务是从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;
}
}
解决方法
当你知道你从 0 开始(图的起源)那么为什么要调用图的每个节点(顶点)。我想你误解了这些问题。您必须在 Origin 0 上应用 BFS。您也可能会得到 IndexOutOfBound Exception,因为图的所有顶点都从 0 到 V-1(含)。我可以看到您将图形顶点视为 1 到 V 包括在内。
newState = state.copyWith(surveys: event.surveys);
...
yield newState;