Implementation of undirected graph breadth-first traversal in C Language
Here we record the breadth-first traversal of undirected graphs.Adjacent tableThe following figure shows an example of the graph used. For details about the Graph Representation, refer to the blog: undirected graph representation: the joining matrix and the joining list, the undirected representation code is encapsulated into the header file.queue.h
.
In addition, the C-language queue problem is also involved. You can refer to the blog: C-loop queue implementation, and do not go into details again. The Code implemented by the loop queue is encapsulated into the header file.graph_represent.h
.
Example of program usage:
Implementation points:
Each fixed point has three states:-1, 0, 1,-1: indicates the node not found; 0: indicates the node that has been found but not processed; 1: indicates the node that has been processed. The "tree edge" is also saved during the traversal process, and the tree edge represents the vertices experienced during the traversal process.
The program framework is as follows:
The Code is as follows:
# Include
# Include
# Include "queue. h "# include" graph_represent.h "void BFS (struct vNode ** adj, int n, int s, int * parent) {int * color = (int *) malloc (sizeof (int) * (n); //-1: not found, 0: found, not processed, 1: int I processed; queue * pending = createQue (n); // create a Queue for (I = 0; I
Value] =-1) {color [w-> value] = 0; add (pending, w-> value); parent [w-> value] = v; /** handle the tree edge here **/} w = w-> next;} printf ("% d", v ); /** process nodes here **/color [v] = 1;} printf ("\ n");} void main () {// obtain the default graph, A total of 7 nodes int n = 7; struct vNode ** adjVertics = default_wraper (); int * parent = (int *) malloc (sizeof (int) * n ); printf ("\ nbreadth first search: \ n"); BFS (adjVertics, n, 2, parent); // traverse from the second node}
Traverse from the second node. The output is: 2 0 1 3 5 4 6