A-C/ex5_1_1.c
2022-05-11 13:33:37 +00:00

150 lines
3.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#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; i<G->n; i++) {
getchar();
printf("输入第 %d 个顶点:", i+1);
scanf("%c", &(G->adjlist[i].data));
G->adjlist[i].firstedge=NULL;
}
for(int i=0; i<G->e; i++){
getchar();
printf("建立第 %d 条边格式顶点1,顶点2", i+1);
scanf("%c,%c",&ch1,&ch2);
for(int j=0; j<G->n; j++){
for(int k=0; k<G->n; 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; i<G->n; 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; i<MAX; i++){
visited[i] = 0;
}
}
void DFS(AdjList G, int v){
EdgeNode *p;
printf("(%d,%c)", v, G->adjlist[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;
}