Input Sample/* 5 0 AB AD ac cd be de *///output/* Please Input the edge x-->y:ab AD AC cd is de A 1 2 3 B 0 4 C 0 3 D 0 2 4 E 1 3 *///DFS test Data/* 8 0 Please Input the Edge x-->y:ab AC BD be DH EH HF HG FC GC CA A 1 2 2 B 0 3 4 C 0 0 5 6 D 1 7 E 1 7 F 2 7 G 2 7 H 3 4 5 6 ABDHEFCG * * #include <iostream> #include <cstdio>using na Mespace std; #define MaxVer 10int Visited[maxver];typedef Char elemtype;//next to the node typedef struct node{int num; struct node *next;} slink;//first knot points Group typedef struct{struct{Elemtype vertex; Slink *first; }ve[maxver]; int Vex,edge,tag;} adjlist;//using a simple structure to build the adjacency table of the diagram void Cregraph (adjlist *g,int n,int m) {g->vex=n; g->tag=m; int e=0; Slink *s,*p,*q; for (int i=0;i<n;i++) {g->ve[i].vertex= ' A ' +i; g->ve[i].first=null; } elemtype x, y; printf ("Please Input the Edge x-->y:"); scanf ("%c%c", &x,&y); while (x!= ' &&y!= ') {e++; s=(Slink *) malloc (sizeof (slink)); s->num=y-' A '; if (g->ve[x-' a '].first==null) {g->ve[x-' a '].first=s; s->next=null; } else{p=g->ve[x-' A '].first; if (p->num>s->num) {s->next=p; g->ve[x-' A '].first=s; } else{q=p->next; while (Q!=null&&q->num<s->num) {p=q; q=q->next; } p->next=s; s->next=q; }} if (! G->tag) {s= (slink *) malloc (sizeof (slink)); s->num=x-' A '; if (g->ve[y-' a '].first==null) {g->ve[y-' a '].first=s;s->next=null;} else{p=g->ve[y-' A '].first; if (p->num>s->num) {s->next=p; g->ve[y-' A '].first=s;} else{ q=p->next; while (Q!=null&&q->num<s->num) {p=q;q=q->next;} p->next=s; s->next=q; }}} GetChar (); scanf ("%c%c", &x,&y); } g->edge=e;} The algorithm for outputting graphs represented by adjacency table void list (Adjlist *g) {slink *p; for (int i=0;i<g->vex;i++) {p=g->ve[i].first; printf ("%c", G->ve[i].vertex); while (p) {printf ("%3d", p->num); p=p->next; } printf ("\ n"); }}void Dfs (adjlist *g,int v) {visited[v]=1; printf ("%c", G->ve[v].vertex); Slink *p; p=g->ve[v].first; while (p) {if (!visited[p->num]) DFS (g,p->num); p=p->next; }}void dfsgraph (adjlist *g) {memset (visited,0,sizeof (visited)); for (int i=0;i<g->vex;i++) if (!visited[i]) DFS (g,i);} int main () {adjlist *g; g= (Adjlist *) malloc (sizeof (adjlist)); int n,m;scanf ("%d%d", &n,&m); GetChar (); Cregraph (G,N,M); List (G); Dfsgraph (G); printf ("\ n"); return 0;}
DFS Traversal of adjacency tables