用C语言写一个用户输入有向图邻接矩阵并遍历的程序,要求能实现两种遍历方式
时间: 2024-03-26 17:40:39 浏览: 65
好的,我来为您编写一个用C语言实现有向图遍历的程序。程序会让用户输入图的邻接矩阵,并根据用户输入创建有向图。然后,程序会实现深度优先遍历和广度优先遍历两种遍历方式。
下面是程序的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
typedef struct Graph {
int numVertices;
bool adjMatrix[MAX_VERTICES][MAX_VERTICES];
} Graph;
Graph* newGraph(int numVertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = false;
}
}
return graph;
}
void addEdge(Graph* graph, int src, int dest) {
graph->adjMatrix[src][dest] = true;
}
void dfs(Graph* graph, int vertex, bool visited[]) {
visited[vertex] = true;
printf("%d ", vertex);
for (int i = 0; i < graph->numVertices; i++) {
if (!visited[i] && graph->adjMatrix[vertex][i]) {
dfs(graph, i, visited);
}
}
}
void bfs(Graph* graph, int vertex, bool visited[]) {
int queue[graph->numVertices];
int front = 0;
int rear = 0;
queue[rear++] = vertex;
visited[vertex] = true;
while (front != rear) {
int v = queue[front++];
printf("%d ", v);
for (int i = 0; i < graph->numVertices; i++) {
if (!visited[i] && graph->adjMatrix[v][i]) {
visited[i] = true;
queue[rear++] = i;
}
}
}
}
int main() {
int numVertices;
printf("请输入图中顶点的数量:");
scanf("%d", &numVertices);
Graph* graph = newGraph(numVertices);
int adjMatrix[numVertices][numVertices];
printf("请输入图的邻接矩阵:\n");
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
scanf("%d", &adjMatrix[i][j]);
if (adjMatrix[i][j]) {
addEdge(graph, i, j);
}
}
}
bool visited[numVertices];
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
printf("深度优先遍历结果:");
for (int i = 0; i < numVertices; i++) {
if (!visited[i]) {
dfs(graph, i, visited);
}
}
printf("\n");
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
printf("广度优先遍历结果:");
for (int i = 0; i < numVertices; i++) {
if (!visited[i]) {
bfs(graph, i, visited);
}
}
printf("\n");
return 0;
}
```
该程序会先要求用户输入图的顶点数量,然后根据顶点数量创建图。接着,程序会要求用户输入图的邻接矩阵,并根据邻接矩阵创建图的边。最后,程序将实现深度优先遍历和广度优先遍历,并输出遍历结果。
注意:在创建图的时候,我们使用邻接矩阵来表示图的边。如果邻接矩阵中的值为1,则表示该边存在;否则,表示该边不存在。在实现深度优先遍历和广度优先遍历时,我们使用一个visited数组来记录每个顶点是否已经被访问过。
阅读全文