#include #include #include #include #define MAX 100 int visited[MAX]; //邻接表 typedef struct node{ //边表 int adjvex; struct node *next; }EdgeNode; typedef struct vexnode{ //顶点表 char data; EdgeNode *firstedge; }VHeadNode; typedef struct{ int n; int e; VHeadNode adjlist[MAX]; //顶点表数组 }adjlist,*AdjList; void CreateAGraph(AdjList G){ char ch1,ch2; EdgeNode *p; printf("请输入顶点数:"); scanf("%d", &G->n); printf("请输入边数:"); scanf("%d", &G->e); printf("\n请输入顶点信息:\n"); for(int i=0; in; i++) { getchar(); printf("输入第 %d 个顶点:", i+1); scanf("%c", &(G->adjlist[i].data)); G->adjlist[i].firstedge=NULL; } for(int i=0; ie; i++){ getchar(); printf("建立第 %d 条边(格式:顶点1,顶点2):", i+1); scanf("%c,%c",&ch1,&ch2); for(int j=0; jn; j++){ for(int k=0; kn; k++){ if(ch1==G->adjlist[j].data && ch2==G->adjlist[k].data){ p=(EdgeNode *)malloc(sizeof(EdgeNode)); p->adjvex = k; p->next = G->adjlist[j].firstedge; G->adjlist[j].firstedge = p; p=(EdgeNode *)malloc(sizeof(EdgeNode)); p->adjvex = j; p->next = G->adjlist[k].firstedge; G->adjlist[k].firstedge = p; } } } } } void DisplayAGraph(AdjList G){ EdgeNode *p; printf("图的邻接表为:\n"); for(int i=0; in; i++){ printf("%2d [%c]", i, G->adjlist[i].data); p = G->adjlist[i].firstedge; while(p!=NULL){ printf("-->[%d]", p->adjvex); p=p->next; } printf("\n"); } } void clear(){ for(int i=0; iadjlist[v].data); visited[v] = 1; p = G->adjlist[v].firstedge; while(p!=NULL){ if(visited[p->adjvex]==0){ DFS(G, p->adjvex); } p=p->next; } } void BFS(AdjList G, int v){ int Qu[MAX], front=0, rear=0; EdgeNode *p; printf("(%d,%c)", v, G->adjlist[v].data); visited[v]=1; rear = (rear + 1) % MAX; Qu[rear] = v; while(front != rear){ front = (front + 1) % MAX; v = Qu[front]; p = G->adjlist[v].firstedge; while(p!=NULL){ if(visited[p->adjvex]==0){ visited[p->adjvex]=1; printf("(%d,%c)", p->adjvex, G->adjlist[p->adjvex].data); rear = (rear + 1) % MAX; Qu[rear]=p->adjvex; } p=p->next; } } } int main(){ int choice; adjlist G; for(;;){ printf("\t\t1.建立图的邻接表\n"); printf("\t\t2.输出图的邻接表\n"); printf("\t\t3.邻接表的深度遍历\n"); printf("\t\t4.邻接表的广度遍历\n"); printf("\t\t0.退出\n"); printf("请选择:"); scanf("%d",&choice); if(choice==0) break; switch (choice) { case 1: CreateAGraph(&G); break; case 2: DisplayAGraph(&G); break; case 3: clear(); printf("深度遍历结果如下:"); DFS(&G, 0); printf("\n"); break; case 4: clear(); printf("广度遍历结果如下:"); BFS(&G, 0); printf("\n"); break; default: break; } printf("请按任意键继续..."); getch(); system("cls"); } printf("感谢使用,再见\n"); return 0; }