Depth-first traversal and breadth-first traversal of graphs based on adjacency table storage

Source: Internet
Author: User

I. Depth-first traversal is a traversal strategy for connected graphs. The basic ideas are as follows:

Set X is the currently visited vertex, and after the access mark has been made to X, select an undetected Edge (x, y) that departs from X. If vertex y is found to have been visited, re-select an undetected edge from X, otherwise along the edge (x, y) to the never visited Y, access to Y and mark it as visited, and then search from Y until all the paths from y have been searched, that is, after all the vertices that are reachable from Y have been accessed, Back to Vertex x, and then select an undetected edge from X. The above process is until all edges from X have been detected.

For example, in:

1. Starting with 0, 0 of the associated vertex 32 is found. Starting from 3, find 1; depart from 1 with no associated vertices. 3. Go back to 3, starting from 3, find 2; Starting from 2, no associated vertices. 4. Go back to 4, 4 departure, find 1, because 1 has been visited, so do not access. So the final order is 0,3,1,2,4. two. Breadth-first traversal is a traversal strategy for connected graphs. The basic ideas are as follows:

1, a vertex V0 departure, and access to this vertex;

2, from V0, access to the V0 of the w1,w2,...,wk of the neighboring points; then, from the W1,w2,..., Wk to access their inaccessible neighboring points;

3. Repeat step 2 until all the vertices have been accessed.

For example, in: 1. Starting from 0, we first find the associated vertex 3,42 of 0. Starting from 3, find 1, 2, start from 4, find 1, but 1 has been traversed, so ignore. 3. Starting from 1, there are no associated vertices; starting from 2, there are no associated vertices. So the final order is 0,3,4,1,2. three. To achieve depth-first traversal and breadth-first traversal, take this no-map example: The implementation code is as follows:
/** adjacency Table Depth-first traversal and breadth-first traversal **/#include<stdio.h>#include<stdlib.h>#defineMaxvex 255#defineTRUE 1#defineFALSE 0typedefCharVertextype;//Vertex typetypedefintBool;  Bool Visited[maxvex]; //Global Array, node access status in the record graphtypedefstructEdgenode {//Edge Table Node    intAdjvex;//Subscript of The adjacency point in the vertex array    structEdgenode *next;//Link field points to next adjacency point}edgenode;typedefstructVertexnode {//head NodeVertextype data;//Vertex InformationEdgenode *firstedge;//Edge Header pointer (pointer to the first arc attached to the vertex)}vertexnode,adjlist[maxvex];//vertex Array (struct array)typedefstructgraph{adjlist adjlist; intNumvertexes,numedges;//the current number of nodes and edges in the graph}graph,*graphadjlist;/** Queue definition and related operations (breadth traversal will be used in this loop queue) **/typedefstructloopqueue{intData[maxvex]; intFront,rear;} Loopqueue,*queue;//Queue StructurevoidInitqueue (Queue &Q) {Q->front=q->rear=0;} Bool Queueempty (Queue&p) {    if(Q->front = = q->rear) {        returnTRUE; }Else{        returnFALSE; }}bool Queuefull (Queue&Q) {    if((q->rear+1)%maxvex = = Q->front) {        returnTRUE; }Else{        returnFALSE; }}/** * Team tail Insert element*/voidEnQueue (Queue &q,inte) {    if(!queuefull (Q)) {Q->data[q->rear] =e; Q->rear = (q->rear+1)%Maxvex; }}/** * Team Header Delete element*/voidDeQueue (Queue &q,int*e) {    if(!Queueempty (Q)) {        *e = q->data[q->Front]; Q->front = (q->front+1)%Maxvex; }}/*************************************************//** * Create adjacency table structure for graphs (here is an example of an no map)*/voidCreatealgraph (Graphadjlist &G) {    intI, j, K; if(g==NULL) {G= (graphadjlist)malloc(sizeof(Graph)); } printf ("Enter the number of nodes and sides of the graph:"); scanf ("%d%d",&g->numvertexes,&g->numedges);    Fflush (stdin); printf ("===========================\n"); printf ("enter data for each vertex: \ n");  for(i=0; i<g->numvertexes; ++i) {printf ("Vertex%d:", i+1); scanf ("%c", & (g->adjlist[i].data)); G->adjlist[i].firstedge =NULL;      Fflush (stdin); } printf ("===========================\n");  for(k=0; k<g->numedges; ++k) {printf ("the vertex number on the input (VI,VJ):"); scanf ("%d%d",&i,&j); Edgenode*ptredgenode = (edgenode*)malloc(sizeof(Edgenode)); Ptredgenode->adjvex =J; Ptredgenode->next = g->Adjlist[i].firstedge; G->adjlist[i].firstedge =Ptredgenode; Ptredgenode= (edgenode*)malloc(sizeof(Edgenode)); Ptredgenode->adjvex =i; Ptredgenode->next = g->Adjlist[j].firstedge; G->adjlist[j].firstedge =Ptredgenode; }}voidDFS (Graphadjlist &g,inti) {Visited[i]=TRUE; printf ("%c", g->adjlist[i].data); Edgenode*p = g->Adjlist[i].firstedge;  while(p) {if(!visited[p->Adjvex]) {DFS (g,p->adjvex);//Recursive depth Traversal} P= p->Next; }}/** * Depth-First traversal*/voidDfstraverse (Graphadjlist &G) {    inti;  for(i=0; i<g->numvertexes; ++i) {Visited[i]= FALSE;//initialize access to array visited the element value is False    }     for(i=0; i<g->numvertexes; ++i) {        if(!visited[i]) {//node has not been accessedDFS (g,i); }    }}/** * Chart breadth-First traversal*/ voidBfstraverse (Graphadjlist &G) {      inti; Queue Q= (Queue)malloc(sizeof(Loopqueue));  for(i=0; i<g->numvertexes; ++i) {Visited[i]=FALSE;          } initqueue (Q);  for(i=0; i<g->numvertexes; ++i) {          if(!Visited[i]) {Visited[i]=TRUE; printf ("%c", g->adjlist[i].data);              EnQueue (Q, i);  while(!Queueempty (Q)) {DeQueue (Q,&i); Edgenode*p = g->Adjlist[i].firstedge;  while(p) {if(!visited[p->Adjvex]) {Visited[p->adjvex] =TRUE; printf ("%c", g->adjlist[p->adjvex].data); EnQueue (Q, p-Adjvex); } P= p->Next; }            }        }      }    }/** * Program Entry*/intMain () {graphadjlist G=NULL;     Createalgraph (G); printf ("\ n The depth-first traversal of the graph is:");     Dfstraverse (G); printf ("\ n The breadth-first traversal of the graph is:");    Bfstraverse (G); printf ("\ n"); return 0;} 

Operation Result:

Depth-first traversal and breadth-first traversal of graphs based on adjacency table storage

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.