前言:
如今姐妹们对“广度优先算法c语言”大致比较着重,你们都想要分析一些“广度优先算法c语言”的相关知识。那么小编也在网上网罗了一些关于“广度优先算法c语言””的相关文章,希望朋友们能喜欢,你们快快来学习一下吧!Breadth First Traversal (or Search) for a graph may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.
广度优先遍历(或搜索)图像可能包含周期,所以我们可能会再次相同的节点。为了避免处理节点不止一次,我们使用一个布尔访问数组。为简单起见,假设所有顶点都可以从顶点开始。
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.
例如,在下面的图,我们从顶点开始遍历2。当我们来到顶点0,我们寻找所有相邻顶点。2也是一个相邻的顶点0。如果我们不标记访问顶点,然后再处理一遍,它将成为一个终止过程。以下图的广度优先遍历2 0 3 1。
import java.util.LinkedList;public class BreadthFirstSearchGraph{ private int V; private LinkedList<Integer>[] adj; public BreadthFirstSearchGraph(int v){ this.V = v; adj = new LinkedList[V]; for (int i = 0; i < V ; i++) { adj[i] = new LinkedList<>(); } } public void addEdge(int v, int w){ adj[v].add(w); } public void bfs(int s) { boolean[] visited = new boolean[V]; LinkedList<Integer> queue = new LinkedList<>(); visited[s] = true; queue.add(s); while(queue.size() != 0){ int r = queue.poll(); System.out.println(" " + r + " "); for (Integer item : adj[r]) { if (!visited[item]){ visited[item] = true; queue.add(item); } } } } public static void main(String[] args) { BreadthFirstSearchGraph g = new BreadthFirstSearchGraph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.bfs(2); }}
标签: #广度优先算法c语言