c语言输出无向图创建及遍历,广度和深度遍历
时间: 2023-09-01 22:07:47 浏览: 128
以下是 C 语言实现无向图的创建及遍历,包括广度优先遍历和深度优先遍历:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
// 邻接矩阵存储无向图
typedef struct Graph {
int vertex_num; // 顶点数
int edge_num; // 边数
int matrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
} Graph;
// 初始化无向图
void init_graph(Graph *g, int vertex_num) {
int i, j;
g->vertex_num = vertex_num;
g->edge_num = 0;
for (i = 0; i < g->vertex_num; i++) {
for (j = 0; j < g->vertex_num; j++) {
g->matrix[i][j] = 0;
}
}
}
// 添加边
void add_edge(Graph *g, int start, int end) {
g->matrix[start][end] = 1;
g->matrix[end][start] = 1;
g->edge_num++;
}
// 深度优先遍历
void dfs(Graph *g, int v, int *visited) {
int i;
visited[v] = 1;
printf("%d ", v);
for (i = 0; i < g->vertex_num; i++) {
if (g->matrix[v][i] == 1 && !visited[i]) {
dfs(g, i, visited);
}
}
}
// 广度优先遍历
void bfs(Graph *g, int v, int *visited) {
int i, queue[MAX_VERTICES], front = 0, rear = 0;
visited[v] = 1;
printf("%d ", v);
queue[rear++] = v;
while (front != rear) {
int cur = queue[front++];
for (i = 0; i < g->vertex_num; i++) {
if (g->matrix[cur][i] == 1 && !visited[i]) {
visited[i] = 1;
printf("%d ", i);
queue[rear++] = i;
}
}
}
}
int main() {
Graph g;
int visited[MAX_VERTICES] = {0};
int vertex_num, edge_num, start, end;
printf("请输入顶点数和边数:");
scanf("%d%d", &vertex_num, &edge_num);
init_graph(&g, vertex_num);
printf("请输入边的起点和终点:\n");
for (int i = 0; i < edge_num; i++) {
scanf("%d%d", &start, &end);
add_edge(&g, start, end);
}
printf("深度优先遍历:");
for (int i = 0; i < g.vertex_num; i++) {
if (!visited[i]) {
dfs(&g, i, visited);
}
}
printf("\n");
for (int i = 0; i < vertex_num; i++) {
visited[i] = 0;
}
printf("广度优先遍历:");
for (int i = 0; i < g.vertex_num; i++) {
if (!visited[i]) {
bfs(&g, i, visited);
}
}
printf("\n");
return 0;
}
```
在运行程序时,输入顶点数和边数,再输入每条边的起点和终点,程序会输出深度优先遍历和广度优先遍历的结果。
阅读全文