This paper illustrates the adjacency table storage and breadth first traversal method of C + + implementation graph. Share to everyone for your reference. Specifically as follows:
Example: Creating a non-direction diagram as shown in the figure
It is known from the above figure that the figure has 5 vertices, a,b,c,d,e respectively, with 6 edges.
Sample input (enter in this format):
5
6
Abcde
0 1
0 2
0 3
2 3
2 4
1 4
Enter end (this row does not have to be entered)
Note: 0 1 indicates that the No. 0 vertex of the graph and the 1th point are connected, as shown in the a->b above
0 2 means that the No. 0 vertex of the graph and the 2nd point are connected, as shown in the a->c above
2 3 means that the 2nd vertex of the graph and the 3rd point are connected, as shown in the c->d above
The implementation code is as follows:
#include <stdio.h> #include <malloc.h> #define Max_vex struct NODE {int ix; * Vertex index * * struct NODE *next; * * Next table node/}edgenode;
/* Table node */typedef struct {char vex; Edgenode *first; /* First TABLE node * *}VERTEX;
/* Table head node/typedef struct {Vertex Vex[max_vex];
int n,e;
}graph;
void Create (GRAPH *g); void BFS (GRAPH *g,int k);
/* Breadth First traversal */int main (int argc, char *argv[]) {GRAPH G;
Create (&G);
BFS (&g,0);
return 0;
} void BFS (GRAPH *g,int k) {Edgenode *p; int Queue[max_vex];
/* Loop queue */int front = -1,rear = -1,amount = 0;
int Visited[max_vex];
int i,j;
for (i = 0; i < Max_vex ++i) visited[i] = 0;
printf ("Access vertex:%c\n", G->vex[k].vex);
Visited[k] = 1; Rear = (rear + 1)% Max_vex;
/* Team/* front = 0;
Queue[rear] = k;
++amount;
while (Amount > 0) {i = Queue[front];/* out team/front = (front + 1)% Max_vex;
--amount;
p = g->vex[i].first; while (p) {if (Visited[p->ix] = = 0) {printf ("Access vertex:%c\n", g>vex[p->ix].vex);
Visited[p->ix] = 1; Rear = (rear + 1)% Max_vex;
* * Team/queue[rear] = p->ix;
++amount;
} p = p->next;
} void Create (GRAPH *g) {printf ("Number of vertices entered: \ n");
scanf ("%d", &g->n);
printf ("Enter number of edges: \ n");
scanf ("%d", &g->e);
GetChar ();
Edgenode *p;
int i,j,k;
for (i = 0; i < g->n ++i)/* Create vertex table/{scanf ("%c", &g->vex[i].vex);
G->vex[i].first = NULL;
for (k = 0; k < g->e; ++k)/* Create a side Table * * * * * Similar to the header creation of the linked list/scanf ("%d%d", &i,&j);
p = (edgenode*) malloc (sizeof (Edgenode));
P->next = g->vex[i].first;
P->ix = j;
G->vex[i].first = p;
p = (edgenode*) malloc (sizeof (Edgenode));
P->next = g->vex[j].first;
P->ix = i;
G->vex[j].first = p; }
}
I hope this article will help you with your C + + programming.