Breadth-first traversal is one of the simplest graph search algorithms, and is also a model of many important graph algorithms.
Representation of graphs
For Figure g= (V,e) (V represents a collection of nodes in the diagram, E represents a collection of all the edges in the graph), which can be expressed in two standard representations:
1. Use the graph as a combination of adjacency lists
For Figure g= (V,e), its adjacency list is represented by a containing | The array adj of the v| list is composed.
For each node u∈v, the adjacency list Adj[u] contains all the nodes that are adjacent to u in Figure G.
2. View the graph as an adjacency matrix
For the adjacency matrix representation, we numbered the node of Figure G as 1,2,...,|. v|, with a | V|x| A matrix of v| to represent figure G, which satisfies the following conditions:
The following shows two representations of the forward graph and the non-direction graph respectively.
Breadth-First traversal
The basic idea of breadth-first traversal is as follows:
1, a vertex V0 departure, and access to this vertex;
2, from V0, access to the V0 of the w1,w2,...,wk of the neighboring points; then, from the W1,w2,..., Wk to access their inaccessible neighboring points;
3. Repeat step 2 until all the vertices have been accessed.
First, we paint each node in white. In the process of algorithm propulsion, when the node is first encountered, its color will change and meet the following conditions:
All the nodes adjacent to the black nodes have been found, and for gray nodes, there may be uncovered white nodes in their neighboring nodes.
Assuming that the input figure g= (V,E) is represented by the adjacency chain list lock, the following is a pseudo-code for BFS in the breadth-first search process.
1 BFS (g,s)2 forEach vertex u∈g.v-{s}3U.color= White4U.d=∞5u.π=NIL6S.color=GRAY7S.d=08s.π=NIL9q=∅Ten ENQUEUE (q,s) One whileq≠∅ Au=DEQUEUE (Q) - forEach V∈g.adj[u] - ifV.color= White theV.color=GRAY -V.d=u.d+1 -v.π=u - ENQUEUE (q,v) +U.color=black
Each of the dots is stored in the attribute U.color, the precursor node of U is stored in the attribute u.π, the attribute U.D records the distance from the source node s to the node U, and a FIFO queue Q is used to manage the gray node set.
Describes the propulsion process of BFS in a sample map.
The nodes are painted grey to make it easier to see the order of propulsion, and the actual algorithm only needs to be painted white or black.
Breadth-first traversal of graphs