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

131 lines
2.6 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 graph
{
int n; //顶点数
int e; //边数
char vexs[MAX]; //顶点数组
int edges[MAX][MAX]; //边的领接矩阵
}graph,*MGraph;
void CreateMGraph(MGraph G){
char ch1,ch2;
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->vexs[i]));
}
for(int i=0; i<G->n; i++){
for(int j=0; j<G->n; j++){
G->edges[i][j]=0;
}
}
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->vexs[j]&&ch2==G->vexs[k]){
G->edges[j][k]=1;
G->edges[k][j]=1; // 无向
}
}
}
}
}
void DisplayMGraph(MGraph G){
printf("图的邻接矩阵为:\n");
for(int i=0; i<G->n; i++){
for(int j=0; j<G->n; j++){
printf("%5d", G->edges[i][j]);
}
printf("\n");
}
}
void clear(){
for(int i=0; i<MAX; i++){
visited[i] = 0;
}
}
void DFS(MGraph G, int v){
printf("%c", G->vexs[v]);
visited[v] = 1;
for(int i=0; i<G->n; i++){
if(G->edges[v][i]!=0 && visited[i]==0){
DFS(G, i);
}
}
}
void BFS(MGraph G, int v){
int Qu[MAX], front=0, rear=0, w;
printf("%c", G->vexs[v]);
visited[v]=1;
rear = (rear + 1) % MAX;
Qu[rear] = v;
while(front != rear){
front = (front + 1) % MAX;
w = Qu[front];
for(int i=0; i<G->n; i++){
if(G->edges[w][i]!=0 && visited[i]==0){
printf("%c", G->vexs[i]);
visited[i]=1;
rear = (rear + 1) % MAX;
Qu[rear] = i;
}
}
}
}
int main(){
int choice;
graph 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:
CreateMGraph(&G);
break;
case 2:
DisplayMGraph(&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;
}