用c语言设计一个基于DOS菜单的应用程序。 有向图的基本操作及应用 ① 创建有向图的邻接矩阵 ② 创建有向图的邻接表 ③ 拓扑排序
时间: 2023-09-05 09:07:50 浏览: 85
基于c语言的有向图的应用程序
4星 · 用户满意度95%
下面是一个基于DOS菜单的有向图应用程序示例,包括有向图邻接矩阵和邻接表的创建和拓扑排序。
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
} ArcNode;
typedef struct VNode {
char data;
ArcNode *firstarc;
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum;
int kind;
} ALGraph;
void CreateGraph(ALGraph *G) {
printf("请输入有向图的顶点数和边数:\n");
scanf("%d%d", &(G->vexnum), &(G->arcnum));
printf("请输入有向图的各个顶点:\n");
for (int i = 0; i < G->vexnum; i++) {
getchar(); //清除缓冲区
scanf("%c", &(G->vertices[i].data));
G->vertices[i].firstarc = NULL;
}
printf("请输入有向边的起点和终点:\n");
for (int i = 0; i < G->arcnum; i++) {
int u, v;
scanf("%d%d", &u, &v);
ArcNode *arc = (ArcNode*)malloc(sizeof(ArcNode));
arc->adjvex = v;
arc->nextarc = G->vertices[u].firstarc;
G->vertices[u].firstarc = arc;
}
}
void PrintAdjMatrix(ALGraph G) {
printf("邻接矩阵为:\n");
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
int flag = 0;
for (ArcNode *arc = G.vertices[i].firstarc; arc != NULL; arc = arc->nextarc) {
if (arc->adjvex == j) {
flag = 1;
break;
}
}
printf("%d ", flag);
}
printf("\n");
}
}
void PrintAdjList(ALGraph G) {
printf("邻接表为:\n");
for (int i = 0; i < G.vexnum; i++) {
printf("%c -> ", G.vertices[i].data);
for (ArcNode *arc = G.vertices[i].firstarc; arc != NULL; arc = arc->nextarc) {
printf("%c ", G.vertices[arc->adjvex].data);
}
printf("\n");
}
}
void TopologicalSort(ALGraph G) {
int indegree[MAX_VERTEX_NUM] = {0};
for (int i = 0; i < G.vexnum; i++) {
for (ArcNode *arc = G.vertices[i].firstarc; arc != NULL; arc = arc->nextarc) {
int j = arc->adjvex;
indegree[j]++;
}
}
int stack[MAX_VERTEX_NUM], top = -1;
for (int i = 0; i < G.vexnum; i++) {
if (indegree[i] == 0) {
stack[++top] = i;
}
}
while (top != -1) {
int i = stack[top--];
printf("%c ", G.vertices[i].data);
for (ArcNode *arc = G.vertices[i].firstarc; arc != NULL; arc = arc->nextarc) {
int j = arc->adjvex;
if (--indegree[j] == 0) {
stack[++top] = j;
}
}
}
}
int main() {
int flag = 1;
ALGraph G;
while (flag) {
system("cls"); //清屏
printf("请选择操作:\n");
printf("1. 创建有向图的邻接矩阵\n");
printf("2. 创建有向图的邻接表\n");
printf("3. 打印有向图的邻接矩阵\n");
printf("4. 打印有向图的邻接表\n");
printf("5. 对有向图进行拓扑排序\n");
printf("0. 退出\n");
switch (getch()) {
case '1':
CreateGraph(&G);
break;
case '2':
CreateGraph(&G);
break;
case '3':
PrintAdjMatrix(G);
getch(); //等待用户按键
break;
case '4':
PrintAdjList(G);
getch(); //等待用户按键
break;
case '5':
TopologicalSort(G);
getch(); //等待用户按键
break;
case '0':
flag = 0;
break;
default:
printf("输入错误,请重新选择!\n");
getch(); //等待用户按键
}
}
return 0;
}
```
阅读全文