[Algorithm] BFS—Breadth First Search

[Algorithm] BFS—Breadth First Search

     1. Introduction to BFS

     2. Connectivity graph

     3. BFS algorithm flow chart

     4. Example: poj3984 Maze Problem

     5. Core code


refer to:

"Introduction to Algorithms"

[Introduction to Algorithms] Breadth/ Breadth First Search (BFS) https://blog.csdn.net/raphealguo/article/details/7523411

Breadth-first search algorithm https://blog.csdn.net/ywjun0919/article/details/8838491

poj3984 Maze problem https://blog.csdn.net/u012679707/article/details/79952123

 

1. Introduction to BFS

The breadth-first search algorithm ( BFS , also known as breadth-first search) is one of the simplest graph search algorithms, and it is also the prototype of many important graph algorithms. Dijkstra's single-source shortest path algorithm and Prim 's minimum spanning tree algorithm both use a similar idea to breadth-first search.

Given a graph G=(V,E) and a source vertex s , breadth-first search explores the edges of G in a systematic way to " discover " all vertices that s can reach, and computes the distance ( minimum number of edges ) , the algorithm can also generate a breadth-first tree rooted at s and including all reachable vertices. For any vertex v reachable from s , the path from s to v in the breadth-first tree corresponds to the shortest path from s to v in the graph G , that is, the path containing the smallest number of edges. The algorithm works for both directed and undirected graphs .

It is called a breadth-first algorithm because the algorithm always expands outward through the boundary between the found and unfound vertices, that is, the algorithm first searches for all vertices with distance k from s , and then searches for and S. other vertices with distance k+1 .

The classic example of BFS is to walk the maze. We start from the starting point and find the shortest distance to the end point . Many shortest path algorithms are established based on the idea of ​​breadth first.

 

2. Connectivity graph

Breadth-first search is a traversal strategy for connected graphs, so it is necessary to briefly explain the graph first.


Figure 2-1  Example of a Connectivity Diagram

As shown in Figure 2-1, this is what we call a connected graph. Here is an undirected graph. Connectivity means that every two points are connected by at least one path. For example, the path from V0 to V4 is V0->V1 -> V4.

Generally, we abbreviate vertices with V, edges with E, and graphs with G(V, E).

 

3. BFS algorithm flow chart

BFS assumes that the input graph G=(V,E) is represented by an adjacency list, and several additional data structures are used for each vertex in the graph. For each vertex u V , its color is stored in the variable color[u] , the parent of node u is stored in the variable π[u] . If u has no parent ( eg u=s or u has not been retrieved ) , then π[u]=NIL , the distance between the source point s and the vertex u calculated by the algorithm is stored in the variable d[u] , the algorithm A first-in-first-out queue Q is used to store the gray node set. where head[Q] represents the head element of the queue Q , Enqueue(Q,v) represents the element v is enqueued, Dequeue(Q) represents the dequeue of the head element; Adj[u] represents the sum of theu is the set of adjacent nodes.

The pseudo code is as follows:

procedure BFS(G,S);

  begin
1. for each node u∈V[G]-{s} do
  begin
  2.color[u]←White;
  3. d[u]←∞;
  4. π [u] ← NIL;
  end;

  5.color[s]←Gray;
  6. d[s]←0;
  7. π [s] ← NIL;
  8. Q←{s}

  9. while Q≠φdo
  begin
  10.u←head[Q];
  11. for each node v∈Adj[u] do
  12. if color[v]=White then
      begin
       13.color[v]←Gray;
       14.d[v]←d[v]+1;
       15. π [v] ← u;
       16.Enqueue(Q,v);
      end;
  17.Dequeue(Q);
  18.color[u]←Black;
  end;
  end;
                                       

                                                       BFS algorithm flow chart

 

4. Examples

Instance search requires a shortest path from V0 to V6 .

                                                 

We use an example diagram to illustrate this process. In the process of searching, all nodes are initially white (representing that all points have not yet begun to search) , and the starting point V 0 is marked as gray (indicating that V 0 is about to be radiated ), and the next step is to search When , we visit all the gray nodes once, then turn them black (indicating that they have been radiated) , and then mark the nodes they can reach as gray (because those nodes are the target points of the next search ), but here is a judgment, just like the example just now, when the V1 node is accessed, its next nodes should be V 0 and V 4 , but V 0 has been dyed black in the front, so it is not will dye it grey. This continues until the target node V 6 is dyed gray, indicating that the next step is the end, and there is no need to search (dye) other nodes. At this time, the search can be ended, and the entire search is over. Then, according to the search process, the shortest path is found in reverse. In Figure 3-1 , the nodes on the final path are marked in green.                                             

                                

                                  

 Example application: poj 3984 maze problem https://blog.csdn.net/u012679707/article/details/79952123


5. Core code
// BFS.c++

//Breadth first search

 
 typedef struct
 {
      int x;
      int y;
 }Node;

 // Vs:startpoint
 // Vd:end point
 int Bfs(Node&Vs,Node& Vd)
 {
      queue<Node> Q;
      Node Vn,Vw; //Vn: current node; Vw: adjacent node
      int i;
   
      //mark
        bool visit[MAX][MAX] ; //The color mark==true indicates that the node has been visited
        Node mother[MAX][MAX]; //Mother node
        int dis[MAX][MAX]; //distance
        
        //Four directions (x,y)
        dir[][2]={ {0,1},{1,0},{0,-1},{-1,0} } ;
        
        //Initial state adds the starting point to the queue
        Q.push(Vs);
        visit[Vs.x][Vs.y]=true;//Set the node has been visited
       //mother[Vs.x][Vs.y]=NIL;
       dis[Vs.x][Vs.y]=0; //The initial distance is 0
        
        while( !Q.empty() )
        {
             // remove the head of the queue
             Vn=Q.front();
              Q.pop();
             
              for(i=0;i<4;i++) //adjacent points in four directions
              {
                     Vw=Node(Vn.x+dir[i][0],Vn.y+dir[i][1] );//Calculate adjacent nodes
                     if(Vw==Vd)//find the end point
                     {
                     //Record the path and add code according to the situation
                     mother[Vs.x][Vs.y]=Vn;
                     dis[Vw.x][Vw.y]=dis[Vn.x][Vn.y]+1;
                     return true;
                     }
                    
                     if(isValid(Vw)&& !visit[Vw.x][Vw.y]) //Vw makes a valid node and is white
                     {
                         Q.push(Vw);//Join the queue                         
                         visit[Vw.x][Vw.y]=true;//Set the node color
                         mother[Vs.x][Vs.y]=Vn;//Parent node
                         dis[Vw.x][Vw.y]=dis[Vn.x][Vn.y]+1;                    
                     }
              }
        }
 return false; //No solution, this has no access   
}
-------------------------------------------          END       -------------------------------------

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324482347&siteId=291194637