Algorithm learning-image breadth-first traversal (BFS) (C ++)
Breadth-first Traversal
Breadth-first traversal is a very common and common graph Traversal method. In addition to BFS, there is also a DFS, that is, the depth-first Traversal method. I will write it in my next blog.
Traversal Process
I believe that anyone reading this blog can understand the storage graph of the adjacent linked list.
If you do not understand, please learn the storage method first. In my previous blog.
Portal: Graphic Representation
Then we assume there is a figure as follows:
Node 1-> 3-> NULL
Node 2-> NULL
Node 3-> 2-> 4-> NULL
Node 4-> 1-> 2-> NULL
In this way, we already know what this figure is.
Suppose we start to traverse from node 1.
First, add Node 1 to the queue, and then add all vertices with node 1 to the queue.
Output and pop-up the first element of the teamNode 1And change the color of Node 1 to black.
Then add the adjacent nodes of the first element to the queue. Then, output and pop up the first element of the team, and so on. Until the queue is empty.
Code Implementation
Below is the implementation of the code I wrote, which is relatively simple.
I have written some comments.
/// Main. cpp // BFS // Created by Alps on 15/3/30. // Copyright (c) 2015 chen. All rights reserved. // # include
# Include
# Ifndef Vertex # define Vertex int # endif # ifndef NumVertex # define NumVertex 4 # endif # define WHITE 0 # define GRAY 1 # define BLACK 2 using namespace std; struct node {int val; int weight; node * next; node (int v, int w): val (v), weight (w), next (NULL) {}}; typedef node * VList; struct TableEntery {VList header; Vertex color;}; typedef TableEntery Table [NumVertex + 1]; void InitTableEntry (Vertex start, Table T) {// init the Graph Vertex OutDegree = 0; VList temp = NULL; for (int I = 1; I <= NumVertex; I ++) {scanf ("% d", & OutDegree ); // input the out degree of vertex T [I]. header = NULL; T [I]. color = WHITE; for (int j = 0; j <OutDegree; j ++) {temp = (VList) malloc (sizeof (struct node )); scanf ("% 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} void BFS (Vertex start, Table T) {queue
Q; Q. push (start); VList temp = NULL; while (! Q. empty () {// if queue is not empty, then the bfs is not over temp = 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 queue T [temp-> val]. color = GRAY; // change the color to gray} temp = temp-> next;} printf ("% d", Q. front (); // output the vertex T [Q. front ()]. color = BLACK; // then change color Q. pop () ;}} int main (int argc, const char * argv []) {Table T; InitTableEntry (1, T); BFS (1, T ); return 0 ;}
The above code is BFS. There are many other implementation methods. Yes.