Breadth-First traversal
Breadth-first traversal is a very common and common way to traverse a graph, except for BFS and DFS, which is the depth-first traversal method, which I will write in my next blog post.
Traversal process
I believe that every person who read this blog can read the adjacency list storage diagram.
Do not understand the person, please first learn the storage method. In my previous blog.
Portal: Diagram Representation method
Then we assume that there is a diagram as follows:
Node 1->3->null
Node 2->null
Node 3->2->4->null
Node 4->1->2->null
So we already know what the map is.
Let's say we go through node 1.
First, the node 1 is grayed out, then added to the queue, then all the points with Node 1 gray are added to the queue.
Output and eject the first element 节点1
of the team and turn the color of node 1 to black.
The adjacent nodes of the first element of the team are then added to the queue. Then continue to output and eject the first element of the team and so on. Until the queue is empty.
Code implementation
Here is what I wrote the code implementation, relatively simple.
I have written some notes.
////Main.cpp//BFS////Created by Alps on 15/3/30.//Copyright (c) 2015 Chen. All rights reserved.//#include <iostream>#include <queue>#ifndef Vertex#define VERTEX int#endif#ifndef Numvertex#define NUMVERTEX 4#endif#define WHITE 0#define GRAY 1#define BLACK 2using namespace STD;structnode{intValintWeight Node* Next; NodeintVintW): Val (v), weight (W), Next (NULL) {}};typedefnode* VList;structtableentery{VList Header; Vertex color;};typedefTableentery table[numvertex+1];voidInittableentry (Vertex start, Table T) {//init the GraphVertex Outdegree =0; VList temp = NULL; for(inti =1; I <= Numvertex; i++) {scanf("%d", &outdegree);//input the out degree of vertexT[i].header = NULL; T[i].color = white; for(intj =0; J < Outdegree; J + +) {temp = (VList)malloc(sizeof(structnode));scanf("%d%d", &temp->val, &temp->weight); Temp->next = T[i].header; T[i].header = temp; }} t[start].color = GRAY;//init The start vertex color to gray}voidBFS (Vertex start, Table T) { queue<Vertex>Q; Q.push (start); VList temp = NULL; while(! Q.empty ()) {//if queue is not empty and then the BFS isn't overtemp = T[q.front ()].header;//find The front of the queue while(temp) {//if the front vertex has next vertex if(T[temp->val].color = = white) {Q.push (temp->val);//push The white vertex to the queueT[temp->val].color = GRAY;//change the color to gray} temp = temp->next; }printf("%d", Q.front ());//output the vertexT[q.front ()].color = BLACK;//then Change ColorQ.pop (); }}intMainintargcConst Char* argv[]) {Table T; Inittableentry (1, T); BFS (1, T);return 0;}
The above code is the BFS. In fact, there are many other implementations. All can.
Algorithm Learning-Graph breadth-first traversal (BFS) (c + +)