The basic idea of width-first search is to add the Source Vertex to a queue and retrieve a vertex from the queue each time, add the neighboring vertex of the vertex that has not been visited to the queue until the queue consumption is complete.
Application
Width-first search solves the shortest path problem. The shortest path algorithm is widely used on the Internet, especially routing. Because routing is efficient, every route path is calculated based on the shortest path. Without the shortest path algorithm, we may not be able to enjoy this fast speed.
In addition, width-first search is also used in the express delivery industry to calculate the shortest path.
Code
Import java. util. stack;/*** Created by caipeichao on 14-6-10. */public class BFS {private int s; private boolean [] visited; private int [] edgeTo; public BFS (Graph G, int s) {this. s = s; visited = new boolean [G.V ()]; // Note: Do not forget this sentence edgeTo = new int [G.V ()]; // note: do not forget this sentence bfs (G);} public void bfs (Graph G) {LinkedQueue
Q = new queue
(); Q. enqueue (s); while (! Q. isEmpty () {int v = q. dequeue (); for (int w: G. adj (v) {if (! Visited [w]) {visited [w] = true; // Note: Do not forget this sentence edgeTo [w] = v; q. enqueue (w) ;}}} public boolean hasPathTo (int v) {return visited [v];} public Iterable
PathTo (int v) {if (! HasPathTo (v) return null; // Note: Do not forget the Stack
Result = new Stack
(); While (v! = S) {result. add (v); v = edgeTo [v];} return result ;}}