建立一个有向图并输出邻接矩阵,然后对其进行深度优先搜索遍历和广度优先搜索遍历 C语言完整代码
时间: 2023-06-13 22:07:35 浏览: 104
图的邻接矩阵表示,深度优先遍历,广度优先遍历实现
以下是一个基于邻接矩阵的有向图的深度优先搜索和广度优先搜索的C语言完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
// 邻接矩阵结构体
typedef struct {
int edges[MAX_VERTICES][MAX_VERTICES];
int n_vertices;
} Graph;
// 初始化图
void initGraph(Graph* g, int n_vertices) {
g->n_vertices = n_vertices;
for (int i = 0; i < n_vertices; i++) {
for (int j = 0; j < n_vertices; j++) {
g->edges[i][j] = 0;
}
}
}
// 添加边
void addEdge(Graph* g, int u, int v) {
g->edges[u][v] = 1;
}
// 输出邻接矩阵
void printGraph(Graph* g) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < g->n_vertices; i++) {
for (int j = 0; j < g->n_vertices; j++) {
printf("%d ", g->edges[i][j]);
}
printf("\n");
}
}
// 深度优先搜索遍历
void dfs(Graph* g, int start, int* visited) {
visited[start] = 1;
printf("%d ", start);
for (int i = 0; i < g->n_vertices; i++) {
if (g->edges[start][i] && !visited[i]) {
dfs(g, i, visited);
}
}
}
// 广度优先搜索遍历
void bfs(Graph* g, int start, int* visited) {
int queue[MAX_VERTICES];
int front = 0, rear = 0;
queue[rear++] = start;
visited[start] = 1;
while (front < rear) {
int current = queue[front++];
printf("%d ", current);
for (int i = 0; i < g->n_vertices; i++) {
if (g->edges[current][i] && !visited[i]) {
visited[i] = 1;
queue[rear++] = i;
}
}
}
}
int main() {
Graph g;
int n_vertices, n_edges;
printf("Enter the number of vertices: ");
scanf("%d", &n_vertices);
printf("Enter the number of edges: ");
scanf("%d", &n_edges);
initGraph(&g, n_vertices);
printf("Enter the edges:\n");
for (int i = 0; i < n_edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
addEdge(&g, u, v);
}
printGraph(&g);
int visited[MAX_VERTICES] = {0};
printf("DFS traversal: ");
dfs(&g, 0, visited);
printf("\n");
for (int i = 0; i < n_vertices; i++) {
visited[i] = 0;
}
printf("BFS traversal: ");
bfs(&g, 0, visited);
printf("\n");
return 0;
}
```
这个程序会先要求用户输入图的顶点数和边数,然后逐个读入每条边,最后输出邻接矩阵,并对其进行深度优先搜索和广度优先搜索遍历。
阅读全文