Data structure (c implementation)-------Graph's breadth-first traversal

Source: Internet
Author: User

[This is my own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020]

Algorithm Description:

The initial state of Figure g is that all vertices have not been accessed, and in g any selected vertex VI is the initial starting point, then the breadth-first traversal can be defined as follows: first, access to the initial starting point VI, and then go to all the adjacency points of VI w1,w2,..., wk; Then, go to W1,W2, ..., all the unreachable vertices of the adjacency of the WK, and so on, until all the vertices in the diagram with the initial point vi have been accessed.

Algorithm implementation:

(1) Accessing the initial vertex VI

(2) Set vertex v visited tag

(3) Vertex v queue

(4) while (team not empty) {

Take out the first vertex of the team I;

Search all the adjacency points of vertex i in turn;

If it is not accessed, the adjacency point is accessed and enqueued.


The source code for the breadth-first traversal of graphs using adjacency matrices is as follows:

/** * Breadth Traverse graph **/void bfs_mg (mgraph mg,int s) {//clear Access flag init_visit ();//define a queue to hold the adjacency vertex of the current node int q[max_vex_num];int front = 0; int rear = 0;int i,j,k;printf ("%c\t", Mg.vexs[s]); visit[s] = 1; q[rear++] = s;//traversal queue while (front < rear) {i = q[front++];for (j = 1; J <= mg.vexnum;j++) {if (visit[j] = = 0 && MG.ARCS[I][J] = = 1) {printf ("%c\t", Mg.vexs[j]); visit[j] = 1; q[rear++] = j;}}}

The source code for the breadth-first traversal of graphs using adjacency tables is as follows:

/** * Breadth Traverse graph **/void Bfs_ag (algraph ag,int s) {arcptr p;//empty access flag init_visit ();//define a queue to hold the adjacency vertex of the current node int q[max_vertex_num]; int front = 0;int Rear = 0;int i,j,k;printf ("%c\t", Ag.vertices[s]); visit[s] = 1; q[rear++] = s;//traversal queue while (front < rear) {i = q[front++];for (P = ag.vertices[i].firstarc;p;p=p->nextarc) {j = P->a Djvex;if (visit[j] = = 0) {printf ("%c\t", ag.vertices[j].vexdata); visit[j] = 1; q[rear++] = j;}}}

Algorithm Description:

For a connected graph with n vertices and e edges, because each base point needs to be enqueued once, the while statement needs to execute n times, and for the adjacency matrix, it is also necessary to execute n times for the neighboring matrices, so the time complexity of the BFS_MG is O (n^2), and for the adjacency table, The number of internal loops depends on the total number of Benzi nodes of each vertex, so the time complexity of Bfs_ag is O (n+e).

As you can see, the breadth-first traversal requires a secondary queue, and an array of flags, so the spatial complexity is O (n).


Full code:

complete code for breadth-first traversal with adjacency matrices:

/* ============================================================================ name:graph.c Author:jesson 20121020 version:1.0 description:create Graph using adjacency Matrix, Ansi-style ================================= =========================================== * * #include <stdio.h> #include <stdlib.h> #define Max_vex_num 50typedef Char vertextype;typedef enum {DG, UDG} graphtype;typedef struct {vertextype vexs[max_vex_num];int Arcs[max_vex _num][max_vex_num];int Vexnum, Arcnum; Graphtype type;} mgraph;//set vertex access flag int visit[max_vex_num];/** * To get the specified vertex subscript in the vertex collection by name * VEX Vertex * return if found, returns subscript, otherwise, 0 */int GETINDEXOFV Exs (char Vex, mgraph *mg) {int i;for (i = 1; I <= mg->vexnum; i++) {if (mg->vexs[i] = = vex) {return i;}} return 0;} /** * Create adjacency Matrix */void create_mg (mgraph *mg) {int I, J, K;int v1, v2, Type;char C1, c2;printf ("Please input graph type DG (0) or UDG (1): "), scanf ("%d ", &type), if (type = = 0) Mg->type = Dg;else if (type = = 1) mg->type= udg;else {printf ("Please input correct graph type DG (0) or UDG (1)!"); return;} printf ("Please input Vexmun:"); scanf ("%d", &mg->vexnum);p rintf ("Please input arcnum:"); scanf ("%d", &mg-& Gt;arcnum); GetChar (); for (i = 1; I <= mg->vexnum; i++) {printf ("Please input%dth vex (char):", I); scanf ("%c", &m G->vexs[i]); GetChar ();} Initialize the adjacency matrix for (i = 1; I <= mg->vexnum; i++) {for (j = 1; J <= mg->vexnum; J + +) {Mg->arcs[i][j] = 0;}} Enter the information for the edge, establish the adjacency matrix for (k = 1; k <= mg->arcnum; k++) {printf ("Please input%dth Arc v1 (char) v2 (char):", k); scanf ("%c %c ", &AMP;C1, &c2); v1 = Getindexofvexs (c1, mg); v2 = Getindexofvexs (c2, MG); if (Mg->type = = 1) mg->arcs[v1][v2] = MG-&GT;ARCS[V2][V1] = 1;elsemg->arcs[v1][v2] = 1;getchar ();}} /** * Print adjacency matrix and vertex information */void print_mg (mgraph MG) {int I, j;if (mg.type = = DG) {printf ("Graph type:direct graph\n");} else{printf ("Graph type:undirect graph\n");} printf ("Graph vertex number:%d\n", Mg.vexnum);p rintf ("graph arc Number:%d\n ", Mg.arcnum);p rintf (" Vertex set:\n "); for (i = 1; I <= mg.vexnum; i++) printf ("%c\t", Mg.vexs[i]);p rintf ("\nadjacency matrix:\n"); for (i = 1; I <= mg.vexnum; i++) {j = 1;for (; J < MG . Vexnum; J + +) {printf ("%d\t", Mg.arcs[i][j]);} printf ("%d\n", Mg.arcs[i][j]);}} /** * Initialize vertex access flag **/void init_visit () {int i;for (i = 0;i < max_vex_num;i++) Visit[i] = 0;} /** * Breadth Traverse graph **/void bfs_mg (mgraph mg,int s) {//clear Access flag init_visit ();//define a queue to hold the adjacency vertex of the current node int q[max_vex_num];int front = 0; int rear = 0;int i,j,k;printf ("%c\t", Mg.vexs[s]); visit[s] = 1; q[rear++] = s;//traversal queue while (front < rear) {i = q[front++];for (j = 1; J <= mg.vexnum;j++) {if (visit[j] = = 0 && MG.ARCS[I][J] = = 1) {printf ("%c\t", Mg.vexs[j]); visit[j] = 1; q[rear++] = j;}}} /** * Main function */int main (void) {mgraph mg;create_mg (&mg);p rint_mg (MG);p rintf ("\nthe result of bfs:\n"); BFS_MG (mg,1); return exit_success;}


complete code for breadth-first traversal with adjacency table:

/* ============================================================================ name:algraph.c author:jess on20121020 Version:Copyright:Your Copyright Notice description:graph using linklist, Ansi-style ============== ============================================================== * * #include <stdio.h> #include <stdlib.h > #include <stdio.h> #define max_vertex_num 50typedef enum {DG, UDG} graphtype;typedef char vertextype;// Table node typedef struct ARCNODE {int adjvex;//adjacency node int weight;//edge weight struct arcnode *nextarc;//Next node pointer} arcnode, *arcptr;//head node Ty pedef struct {vertextype vexdata;int id; Arcptr Firstarc;} vnode;//head node array typedef struct {Vnode vertices[max_vertex_num];int vexnum, Arcnum; Graphtype type;}  Algraph;int visit[max_vertex_num];/** * gets subscript */int getindexofvexs (char vex, algraph *ag) in the vertex array based on the vertex character {int i;for (i = 1; i <= ag->vexnum; i++) {if (Ag->vertices[i].vexdata = = vex) {return i;}} return 0;} /** * Create adjacency table */void Create_ag (algraph *ag) {ARCPTR P,q;int I, J, K, type; Vertextype v1, v2;printf ("Please input graph type UG (0) or UDG (1):"); scanf ("%d", &type); if (type = = 0) Ag->type = d G;else if (type = = 1) Ag->type = udg;else {printf ("Please input correct graph type UG (0) or UDG (1)!"); return;} printf ("Please input vexnum:"); scanf ("%d", &ag->vexnum);p rintf ("Please input arcnum:"); scanf ("%d", &ag-  >arcnum); GetChar (); for (i = 1; I <= ag->vexnum; i++) {printf ("Please input the%dth vex (char):", I); scanf ("%c", &ag->vertices[i].vexdata); GetChar (); Ag->vertices[i].firstarc = NULL;} for (k = 1; k <= ag->arcnum; k++) {printf ("Please input the%dth Arc v1 (char) v2 (char):", k); scanf ("%c%c", &v1 , &v2); i = Getindexofvexs (v1, ag); j = Getindexofvexs (v2, AG);//create adjacency table according to the type of diagram//Method 1, insert into the link header/*if (ag->type = DG) {//Map p = (arcptr) malloc (sizeof (Arcnode));p->adjvex = J;p->nextarc = ag->vertices[i].firstarc; Ag->vertices[i].firstarc = P;} else {//no graph P = (arcptr) malloc (sizeof (Arcnode));P->adjvex = J;p->nextarc = ag->vertices[i].firstarc; Ag->vertices[i].firstarc = P;p = (arcptr) malloc (sizeof (Arcnode));p->adjvex = I;p->nextarc = Ag->vertices[j ].firstarc; Ag->vertices[j].firstarc = P;} *///Method 2, insert to the end of the list if (Ag->type = = DG) {//P = (arcptr) malloc (sizeof (Arcnode));p->adjvex = j;//table is empty if (ag-> Vertices[i].firstarc = = NULL) {Ag->vertices[i].firstarc = P;} else{//find the last table node q = ag->vertices[i].firstarc;while (Q->nextarc! = NULL) {q = Q->nextarc;} Q->nextarc = P;} P->nextarc = NULL;} else {//no graph P = (arcptr) malloc (sizeof (Arcnode));p->adjvex = j;//table is empty if (Ag->vertices[i].firstarc = = null) {ag-> Vertices[i].firstarc = P;} else{//find the last table node q = ag->vertices[i].firstarc;while (Q->nextarc! = NULL) {q = Q->nextarc;} Q->nextarc = P;} P->nextarc = Null;p = (arcptr) malloc (sizeof (Arcnode));p->adjvex = i;//table is empty if (Ag->vertices[j].firstarc = = null) {Ag->vertices[j].firstarc = p;} else{//find the last table node q = ag->vertices[j].firstarc;while(Q->nextarc! = NULL) {q = Q->nextarc;} Q->nextarc = P;} P->nextarc = NULL;} GetChar ();}}  /** * Output Graph related information */void print_ag (algraph AG) {arcptr p;int i;if (ag.type = DG) {printf ("Graph type:direct graph\n");} else {printf ("Graph type:undirect graph\n");} printf ("Graph vertex number:%d\n", Ag.vexnum);p rintf ("graph arc Number:%d\n", Ag.arcnum);p rintf ("vertex set: \ n"); for ( i = 1; I <= ag.vexnum; i++) printf ("%c\t", Ag.vertices[i].vexdata);p rintf ("\nadjacency list:\n"); for (i = 1; I <= ag.vexnum; i++) {printf ("%d ", i);p = Ag.vertices[i].firstarc;while (P! = NULL) {printf ("-->%d ", P->adjvex);p = P->nextarc;} printf ("\ n");}} /** * Initialize vertex access flag **/void init_visit () {int i;for (i = 0;i < max_vertex_num;i++) Visit[i] = 0;} /** * Breadth Traverse graph **/void Bfs_ag (algraph ag,int s) {arcptr p;//empty access flag init_visit ();//define a queue to hold the adjacency vertex of the current node int q[max_vertex_num]; int front = 0;int Rear = 0;int i,j,k;printf ("%c\t", Ag.vertices[s]); visit[s] = 1; q[rear++] = s;//traversal queue while (front < rear) {i = Q[front++];for (p = ag.vertices[i].firstarc;p;p=p->nextarc) {j = p->adjvex;if (visit[j] = = 0) {printf ("%c\t", Ag.vertices[j]. Vexdata); visit[j] = 1; q[rear++] = j;}}} int main (void) {algraph ag;create_ag (&ag);p Rint_ag (AG);p rintf ("\nthe result of bfs:\n"); Bfs_ag (ag,1); return exit_success;}



Data structure (c implementation)-------Graph's breadth-first traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.