编程实现图的遍历图算法,按图的深度优先搜索算法和广度优先搜索算法遍历写出代码c语言
时间: 2023-11-10 07:35:02 浏览: 102
图的深度、广度优先遍历(c语言)
5星 · 资源好评率100%
好的,以下是C语言实现图的遍历算法,包括深度优先搜索算法和广度优先搜索算法。
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct Graph {
int numVertices;
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} Graph;
typedef struct Queue {
int items[MAX_VERTICES];
int front;
int rear;
} Queue;
void initGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int 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) {
printf("Adjacency Matrix:\n\n");
for (int i = 0; i < graph->numVertices; i++) {
for (int j = 0; j < graph->numVertices; j++) {
printf("%d ", graph->adjMatrix[i][j]);
}
printf("\n");
}
}
void dfs(Graph* graph, int vertex, int* visited) {
visited[vertex] = 1;
printf("%d ", vertex);
for (int i = 0; i < graph->numVertices; i++) {
if (graph->adjMatrix[vertex][i] == 1 && visited[i] == 0) {
dfs(graph, i, visited);
}
}
}
void bfs(Graph* graph, int startVertex, int* visited) {
Queue queue;
queue.front = 0;
queue.rear = -1;
queue.items[++queue.rear] = startVertex;
visited[startVertex] = 1;
while (queue.front <= queue.rear) {
int currentVertex = queue.items[queue.front++];
printf("%d ", currentVertex);
for (int i = 0; i < graph->numVertices; i++) {
if (graph->adjMatrix[currentVertex][i] == 1 && visited[i] == 0) {
visited[i] = 1;
queue.items[++queue.rear] = i;
}
}
}
}
int main() {
Graph graph;
int numVertices, numEdges;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
initGraph(&graph, numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);
for (int i = 0; i < numEdges; i++) {
int src, dest;
printf("Enter edge %d (source, destination): ", i + 1);
scanf("%d %d", &src, &dest);
addEdge(&graph, src, dest);
}
printGraph(&graph);
int visited[MAX_VERTICES];
for (int i = 0; i < graph.numVertices; i++) {
visited[i] = 0;
}
printf("\nDFS Traversal: ");
for (int i = 0; i < graph.numVertices; i++) {
if (visited[i] == 0) {
dfs(&graph, i, visited);
}
}
printf("\nBFS Traversal: ");
for (int i = 0; i < graph.numVertices; i++) {
visited[i] = 0;
}
bfs(&graph, 0, visited);
return 0;
}
```
在这个程序中,我们首先定义了一个Graph结构体,其中包含了图的邻接矩阵和节点数。我们使用initGraph函数初始化图,并使用addEdge函数添加边。然后,我们使用printGraph函数打印邻接矩阵。
在dfs函数中,我们使用递归遍历图。首先将当前节点标记为已访问,并打印出该节点。然后,我们遍历图中所有未访问的邻居节点,并对每个邻居节点递归调用dfs函数。
在bfs函数中,我们使用队列数据结构遍历图。我们从起始节点开始,并将其标记为已访问。然后,我们将其入队,并遍历队列中的所有节点。对于每个已访问但未加入队列的邻居节点,我们将其标记为已访问,并将其入队。
最后,我们在main函数中调用dfs函数和bfs函数遍历整个图。
阅读全文