void creatGraph(Graph* G, VertexType ver[], VertexType edge[][2]); void DFS(Graph* G, int k, int*_visit, char** res); void BFS(Graph* G, int*_visit, char res[]); void DestroyGraph(Graph*G); void Print(Graph*G);用c语言补全这些函数代码
时间: 2024-02-12 21:05:18 浏览: 97
C语言中实现图(Graph)
下面是这些函数的代码实现:
```c
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef char VertexType; // 顶点类型
typedef struct {
VertexType vexs[MAX_VERTEX_NUM]; // 顶点数组
int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vexnum, arcnum; // 顶点数,边数
} Graph;
// 创建图
void creatGraph(Graph* G, VertexType ver[], VertexType edge[][2]) {
int i, j, k;
G->vexnum = sizeof(ver) / sizeof(VertexType);
G->arcnum = sizeof(edge) / sizeof(VertexType) / 2;
for (i = 0; i < G->vexnum; i++) {
G->vexs[i] = ver[i]; // 顶点数组赋值
}
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
G->arcs[i][j] = 0; // 初始化邻接矩阵
}
}
for (k = 0; k < G->arcnum; k++) {
i = j = -1;
// 查找边的两个顶点在顶点数组中的下标
for (int l = 0; l < G->vexnum; l++) {
if (edge[k][0] == G->vexs[l]) {
i = l;
}
if (edge[k][1] == G->vexs[l]) {
j = l;
}
}
if (i != -1 && j != -1) {
G->arcs[i][j] = G->arcs[j][i] = 1; // 无向图,两个方向都要标记
}
}
}
// 深度优先遍历
void DFS(Graph* G, int k, int*_visit, char** res) {
int i;
res[*_visit] = &(G->vexs[k]); // 将遍历到的顶点存入 res 数组
*_visit += 1;
_visit[k] = 1; // 标记该顶点已被访问
for (i = 0; i < G->vexnum; i++) {
if (G->arcs[k][i] && !_visit[i]) {
DFS(G, i, _visit, res); // 递归访问邻接顶点
}
}
}
// 广度优先遍历
void BFS(Graph* G, int*_visit, char res[]) {
int i, j, k;
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
for (i = 0; i < G->vexnum; i++) {
if (!_visit[i]) {
res[rear++] = G->vexs[i]; // 将未被访问的顶点加入队列
_visit[i] = 1; // 标记该顶点已被访问
}
while (front < rear) {
k = queue[front++]; // 出队一个顶点
for (j = 0; j < G->vexnum; j++) {
if (G->arcs[k][j] && !_visit[j]) {
res[rear++] = G->vexs[j]; // 将邻接顶点加入队列
_visit[j] = 1; // 标记该顶点已被访问
}
}
}
}
}
// 销毁图
void DestroyGraph(Graph*G) {
G->vexnum = 0;
G->arcnum = 0;
}
// 打印图
void Print(Graph*G) {
int i, j;
printf("顶点数:%d,边数:%d\n", G->vexnum, G->arcnum);
printf("顶点数组:");
for (i = 0; i < G->vexnum; i++) {
printf("%c ", G->vexs[i]);
}
printf("\n邻接矩阵:\n");
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
printf("%d ", G->arcs[i][j]);
}
printf("\n");
}
}
```
阅读全文