Recursive depth-first traversal algorithm
1#include <stdio.h>2#include <malloc.h>3 #defineMAXV 1004 #defineINF 327675typedefstructAnode6 {7 intAdjvex;8 intweight;9 structAnode *Nextarc;Ten } Arcnode; One Atypedefstruct - { - intcount; theArcnode *Firstarc; - } Vnode; - -typedefstruct + { - Vnode ADJLIST[MAXV]; + intN, E; A }adjgraph; at - intVISIT[MAXV] = {0 }; - - voidCreateadj (adjgraph* &g,intA[MAXV][MAXV],intNinte); - voidDFS (Adjgraph *g,intv); - in intMain () - { toAdjgraph *G; + intn =6, E =Ten; - intA[MAXV][MAXV] = {{0,5Inf7, INF, INF}, the{INF,0,4, INF, INF, INF},{8Inf0, INF, INF,9 }, *{INF, INF,5,0,5},{INF, INF, INF,5,0, INF},{3, INF, INF, INF,1,0 } }; $ Createadj (G, A, N, e);Panax Notoginsengprintf"DFS algorithm starting from 0:"); -DFS (G,0); theprintf"\ n"); + return 0; A } the + voidDFS (Adjgraph *g,intV//recursive Depth-first traversal algorithm - { $Arcnode *p; $printf"%d", v); -VISIT[V] =1; -p = g->Adjlist[v].firstarc; the while(P! =NULL) - {Wuyi if(Visit[p->adjvex] = =0) theDFS (G, p->Adjvex); -p = p->Nextarc; Wu } - } About $ voidCreateadj (adjgraph* &g,intA[MAXV][MAXV],intNintE//creating adjacency tables for graphs - { -Arcnode *p; -G = (adjgraph*) malloc (sizeof(Adjgraph)); A for(inti =0; I < n; ++i) +G->adjlist[i].firstarc =NULL; the for(inti =0; I < n; ++i) - for(intj = N-1; J >=0; --j) $ if(A[i][j]! =0&& A[i][j]! =INF) the { thep = (Arcnode *) malloc (sizeof(Arcnode)); theP->weight =A[i][j]; theP->adjvex =J; -P->nextarc = g->Adjlist[i].firstarc; inG->adjlist[i].firstarc =p; the } theG->n =N; AboutG->e =e; the}
Operation Result:
"Figure" Experiment two: Traversing algorithm of realization graph