Algorithm 7-4: width-first search

Source: Internet
Author: User

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 ;}}
     
    
   
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.