用C语言建立任意顶点不小于7的无向图,画出无向图,采用邻接矩阵存储,完成以下操作: (1)对该图进行深度优先遍历,并输出遍历结果; (2)对该图进行广度优先遍历,并输出遍历结果。
时间: 2024-05-11 15:18:33 浏览: 164
无向图的邻接矩阵表示
3星 · 编辑精心推荐
以下用C语言实现的任意顶点不小于7的无向图的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 20
typedef struct {
int vertex[MAX_VERTEX_NUM];
int arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, arc_num;
} MGraph;
bool visited[MAX_VERTEX_NUM];
void createGraph(MGraph *G) {
int i, j, k, v1, v2;
printf("请输入顶点数和边数:");
scanf("%d%d", &G->vertex_num, &G->arc_num);
printf("请输入%d个顶点:", G->vertex_num);
for (i = 0; i < G->vertex_num; i++) {
scanf("%d", &G->vertex[i]);
}
for (i = 0; i < G->vertex_num; i++) {
for (j = 0; j < G->vertex_num; j++) {
G->arc[i][j] = 0;
}
}
printf("请输入%d条边:\n", G->arc_num);
for (k = 0; k < G->arc_num; k++) {
scanf("%d%d", &v1, &v2);
i = -1, j = -1;
for (int l = 0; l < G->vertex_num; l++) {
if (G->vertex[l] == v1) {
i = l;
}
if (G->vertex[l] == v2) {
j = l;
}
if (i != -1 && j != -1) {
break;
}
}
G->arc[i][j] = 1;
G->arc[j][i] = 1;
}
}
void DFS(MGraph *G, int i) {
int j;
visited[i] = true;
printf("%d ", G->vertex[i]);
for (j = 0; j < G->vertex_num; j++) {
if (G->arc[i][j] == 1 && !visited[j]) {
DFS(G, j);
}
}
}
void DFSTraverse(MGraph *G) {
int i;
for (i = 0; i < G->vertex_num; i++) {
visited[i] = false;
}
for (i = 0; i < G->vertex_num; i++) {
if (!visited[i]) {
DFS(G, i);
}
}
}
void BFS(MGraph *G, int i) {
int queue[MAX_VERTEX_NUM];
int front = 0, rear = 0;
int j, k;
printf("%d ", G->vertex[i]);
visited[i] = true;
queue[rear++] = i;
while (front != rear) {
j = queue[front++];
for (k = 0; k < G->vertex_num; k++) {
if (G->arc[j][k] == 1 && !visited[k]) {
printf("%d ", G->vertex[k]);
visited[k] = true;
queue[rear++] = k;
}
}
}
}
void BFSTraverse(MGraph *G) {
int i;
for (i = 0; i < G->vertex_num; i++) {
visited[i] = false;
}
for (i = 0; i < G->vertex_num; i++) {
if (!visited[i]) {
BFS(G, i);
}
}
}
int main() {
MGraph G;
createGraph(&G);
printf("深度优先遍历:");
DFSTraverse(&G);
printf("\n广度优先遍历:");
BFSTraverse(&G);
return 0;
}
```
其中,`createGraph`函数用来创建无向图,`DFS`函数用来进行深度优先遍历,`DFSTraverse`函数用来对整个图进行深度优先遍历,`BFS`函数用来进行广度优先遍历,`BFSTraverse`函数用来对整个图进行广度优先遍历。
输入输出示例:
```
请输入顶点数和边数:7 9
请输入7个顶点:1 2 3 4 5 6 7
请输入9条边:
1 2
1 3
1 4
2 5
2 6
3 6
4 7
5 7
6 7
深度优先遍历:1 2 5 7 6 3 4
广度优先遍历:1 2 3 4 5 6 7
```
阅读全文