//输入样例 /* 5 0 AB AD AC CD BE DE */ //输出 /* Please Input the edge x-->y:AB AD AC CD BE DE A 1 2 3 B 0 4 C 0 3 D 0 2 4 E 1 3 */ //dfs测试数据 /* 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 namespace std; #define MAXVER 10 int visited[MAXVER]; typedef char Elemtype; //接下来要连的结点 typedef struct node{ int num; struct node *next; }slink; //首结点数组 typedef struct{ struct{ Elemtype vertex; slink *first; }ve[MAXVER]; int vex,edge,tag; }adjlist; //使用简单结构建立图的邻接表 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; } //输出用邻接表表示的图的算法 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 bfs(adjlist *G,int v) { int queue[MAXVER]; slink *p; int front,rear,i; front=rear=0; queue[rear++]=v; while(front!=rear) { v=queue[front++]; visited[v]=1; printf("%c",G->ve[v].vertex); p=G->ve[v].first; while(p) { for(i=0;i<rear;i++) if(p->num==queue[i]) break; if(i>=rear) queue[rear++]=p->num; p=p->next; } } } void bfsgraph(adjlist *G) { for(int i=0;i<G->vex;i++) if(!visited[i]) bfs(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); bfsgraph(G); printf("\n"); return 0; }