能否提供一个用C语言实现的邻接矩阵遍历
时间: 2025-01-20 11:17:27 浏览: 20
当然可以,以下是一个用C语言实现的邻接矩阵遍历的示例代码。这个示例代码展示了如何使用邻接矩阵表示图,并进行深度优先搜索(DFS)和广度优先搜索(BFS)遍历。
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
// 定义图的结构
typedef struct {
int numVertices;
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} Graph;
// 初始化图
void initGraph(Graph *graph, int numVertices) {
int i, j;
graph->numVertices = numVertices;
for (i = 0; i < numVertices; i++) {
for (j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = 0;
}
}
}
// 添加边
void addEdge(Graph *graph, int src, int dest) {
graph->adjMatrix[src][dest] = 1;
graph->adjMatrix[dest][src] = 1; // 无向图
}
// 打印邻接矩阵
void printGraph(Graph *graph) {
int i, j;
for (i = 0; i < graph->numVertices; i++) {
for (j = 0; j < graph->numVertices; j++) {
printf("%d ", graph->adjMatrix[i][j]);
}
printf("\n");
}
}
// 深度优先搜索
void DFS(Graph *graph, int startVertex, bool visited[]) {
int i;
printf("%d ", startVertex);
visited[startVertex] = true;
for (i = 0; i < graph->numVertices; i++) {
if (graph->adjMatrix[startVertex][i] && !visited[i]) {
DFS(graph, i, visited);
}
}
}
// 广度优先搜索
void BFS(Graph *graph, int startVertex, bool visited[]) {
int queue[MAX_VERTICES];
int front = 0, rear = 0;
int i, currentVertex;
visited[startVertex] = true;
queue[rear++] = startVertex;
while (front < rear) {
currentVertex = queue[front++];
printf("%d ", currentVertex);
for (i = 0; i < graph->numVertices; i++) {
if (graph->adjMatrix[currentVertex][i] && !visited[i]) {
visited[i] = true;
queue[rear++] = i;
}
}
}
}
int main() {
Graph graph;
int numVertices = 5;
initGraph(&graph, numVertices);
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 4);
addEdge(&graph, 1, 2);
addEdge(&graph, 1, 3);
addEdge(&graph, 1, 4);
addEdge(&graph, 2, 3);
addEdge(&graph, 3, 4);
printf("邻接矩阵:\n");
printGraph(&graph);
bool visited[MAX_VERTICES] = {false};
printf("深度优先搜索:\n");
DFS(&graph, 0, visited);
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
printf("\n广度优先搜索:\n");
BFS(&graph, 0, visited);
return 0;
}
```
这个示例代码展示了如何使用邻接矩阵表示图,并进行深度优先搜索(DFS)和广度优先搜索(BFS)遍历。
阅读全文
相关推荐

















