使用邻接矩阵创建一个图,并对这个图进行深度优先遍历和广度优先遍历。用c语言编写代码
时间: 2024-02-09 13:12:33 浏览: 76
图的深度优先遍历与广度优先遍历(C语言实现)
5星 · 资源好评率100%
好的,下面是使用邻接矩阵创建一个图,并对这个图进行深度优先遍历和广度优先遍历的C语言代码。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100 //最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; //存放顶点的数组
int arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //存放邻接矩阵的二维数组
int vertex_num, arc_num; //顶点数和边数
} Graph;
int visited[MAX_VERTEX_NUM]; //全局数组,存放是否被访问过
//初始化图
void initGraph(Graph *g) {
int i, j;
for (i = 0; i < MAX_VERTEX_NUM; i++) {
g->vertex[i] = 0;
visited[i] = 0;
for (j = 0; j < MAX_VERTEX_NUM; j++) {
g->arc[i][j] = 0;
}
}
g->vertex_num = 0;
g->arc_num = 0;
}
//添加顶点
void addVertex(Graph *g, int v) {
g->vertex[g->vertex_num++] = v;
}
//添加边
void addArc(Graph *g, int v1, int v2) {
g->arc[v1][v2] = 1;
g->arc[v2][v1] = 1; //无向图,所以要把两个方向的边都加上
g->arc_num++;
}
//打印图
void printGraph(Graph *g) {
int i, j;
printf("顶点数:%d,边数:%d\n", g->vertex_num, g->arc_num);
printf("顶点:");
for (i = 0; i < g->vertex_num; i++) {
printf("%d ", g->vertex[i]);
}
printf("\n邻接矩阵:\n");
for (i = 0; i < g->vertex_num; i++) {
for (j = 0; j < g->vertex_num; j++) {
printf("%d ", g->arc[i][j]);
}
printf("\n");
}
}
//深度优先遍历
void dfs(Graph *g, int v) {
int i;
visited[v] = 1;
printf("%d ", g->vertex[v]);
for (i = 0; i < g->vertex_num; i++) {
if (g->arc[v][i] && !visited[i]) {
dfs(g, i);
}
}
}
//广度优先遍历
void bfs(Graph *g, int v) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0; //队列
int i, w;
visited[v] = 1;
printf("%d ", g->vertex[v]);
queue[rear++] = v;
while (front != rear) {
w = queue[front++];
for (i = 0; i < g->vertex_num; i++) {
if (g->arc[w][i] && !visited[i]) {
visited[i] = 1;
printf("%d ", g->vertex[i]);
queue[rear++] = i;
}
}
}
}
int main() {
Graph g;
initGraph(&g);
addVertex(&g, 0);
addVertex(&g, 1);
addVertex(&g, 2);
addVertex(&g, 3);
addVertex(&g, 4);
addArc(&g, 0, 1);
addArc(&g, 0, 2);
addArc(&g, 0, 3);
addArc(&g, 1, 4);
addArc(&g, 2, 3);
addArc(&g, 3, 4);
printGraph(&g);
printf("深度优先遍历:");
dfs(&g, 0);
printf("\n广度优先遍历:");
bfs(&g, 0);
printf("\n");
return 0;
}
```
这段代码创建了一个无向图,其中顶点为0、1、2、3、4,边为0-1、0-2、0-3、1-4、2-3、3-4。然后对这个图进行了深度优先遍历和广度优先遍历。
阅读全文