1、 编程实现图的遍历图算法(按图的深度优先搜索算法和广度优先搜索算法遍历);c语言代码
时间: 2023-07-26 12:09:25 浏览: 110
以下是C语言实现图的深度优先搜索算法和广度优先搜索算法遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct ArcNode { // 弧结点
int adjvex; // 该弧所指向的顶点的位置
struct ArcNode *nextarc; // 指向下一条弧的指针
} ArcNode;
typedef struct VNode { // 顶点结点
int data; // 顶点的数据
ArcNode *firstarc; // 指向第一条依附于该顶点的弧的指针
} VNode, AdjList[MAX_VERTEX_NUM];
typedef struct { // 图
AdjList vertices; // 顶点数组
int vexnum, arcnum; // 顶点数和弧数
} Graph;
// 初始化图
void InitGraph(Graph *G) {
int i;
G->vexnum = G->arcnum = 0;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
G->vertices[i].data = 0;
G->vertices[i].firstarc = NULL;
}
}
// 添加顶点
void AddVertex(Graph *G, int v) {
G->vertices[G->vexnum].data = v;
G->vexnum++;
}
// 添加弧
void AddArc(Graph *G, int v, int w) {
ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = w;
p->nextarc = G->vertices[v].firstarc;
G->vertices[v].firstarc = p;
G->arcnum++;
}
// 深度优先搜索算法遍历
void DFS(Graph *G, int v, int visited[]) {
visited[v] = 1;
printf("%d ", G->vertices[v].data);
ArcNode *p = G->vertices[v].firstarc;
while (p != NULL) {
if (visited[p->adjvex] == 0) {
DFS(G, p->adjvex, visited);
}
p = p->nextarc;
}
}
// 深度优先搜索遍历图
void DFSTraverse(Graph *G) {
int visited[MAX_VERTEX_NUM] = {0};
int i;
for (i = 0; i < G->vexnum; i++) {
if (visited[i] == 0) {
DFS(G, i, visited);
}
}
}
// 广度优先搜索算法遍历
void BFS(Graph *G, int v, int visited[]) {
int queue[MAX_VERTEX_NUM];
int front = 0, rear = 0;
visited[v] = 1;
printf("%d ", G->vertices[v].data);
queue[rear++] = v;
while (front < rear) {
int w = queue[front++];
ArcNode *p = G->vertices[w].firstarc;
while (p != NULL) {
if (visited[p->adjvex] == 0) {
visited[p->adjvex] = 1;
printf("%d ", G->vertices[p->adjvex].data);
queue[rear++] = p->adjvex;
}
p = p->nextarc;
}
}
}
// 广度优先搜索遍历图
void BFSTraverse(Graph *G) {
int visited[MAX_VERTEX_NUM] = {0};
int i;
for (i = 0; i < G->vexnum; i++) {
if (visited[i] == 0) {
BFS(G, i, visited);
}
}
}
// 测试
int main() {
Graph G;
InitGraph(&G);
AddVertex(&G, 1);
AddVertex(&G, 2);
AddVertex(&G, 3);
AddVertex(&G, 4);
AddVertex(&G, 5);
AddArc(&G, 0, 1);
AddArc(&G, 0, 2);
AddArc(&G, 1, 2);
AddArc(&G, 2, 0);
AddArc(&G, 2, 3);
AddArc(&G, 3, 3);
AddArc(&G, 3, 4);
printf("深度优先搜索遍历结果:");
DFSTraverse(&G);
printf("\n广度优先搜索遍历结果:");
BFSTraverse(&G);
return 0;
}
```
以上代码实现了图的深度优先搜索算法和广度优先搜索算法遍历。
阅读全文