用C语言编程实现下列程序:1.初始化邻接矩阵表示的无向图。2.实现无向图的深度优先遍历。3.实现无向图的广度优先遍历。4.用prim算法求最小生成树
时间: 2024-03-23 21:39:41 浏览: 74
用C语言写的一些程序
好的,我会尽力回答你的问题。
以下是用 C 语言编程实现的程序,实现了邻接矩阵表示的无向图初始化、深度优先遍历、广度优先遍历和 Prim 算法求最小生成树。
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
#define INF 0x3f3f3f3f // 无穷大
typedef struct Graph {
int vexNum; // 顶点数
int arcNum; // 边数
int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
} Graph;
// 初始化无向图
void initGraph(Graph *graph) {
printf("请输入顶点数和边数:\n");
scanf("%d %d", &graph->vexNum, &graph->arcNum);
for (int i = 0; i < graph->vexNum; i++) {
for (int j = 0; j < graph->vexNum; j++) {
graph->arcs[i][j] = INF;
}
}
printf("请输入每条边的起点、终点和权值:\n");
for (int k = 0; k < graph->arcNum; k++) {
int i, j, w;
scanf("%d %d %d", &i, &j, &w);
graph->arcs[i][j] = w;
graph->arcs[j][i] = w;
}
}
// 深度优先遍历
void dfs(Graph *graph, int v, bool visited[]) {
visited[v] = true;
printf("%d ", v);
for (int i = 0; i < graph->vexNum; i++) {
if (graph->arcs[v][i] != INF && !visited[i]) {
dfs(graph, i, visited);
}
}
}
// 广度优先遍历
void bfs(Graph *graph, int v, bool visited[]) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
visited[v] = true;
queue[rear++] = v;
while (front < rear) {
int u = queue[front++];
printf("%d ", u);
for (int i = 0; i < graph->vexNum; i++) {
if (graph->arcs[u][i] != INF && !visited[i]) {
visited[i] = true;
queue[rear++] = i;
}
}
}
}
// Prim 算法求最小生成树
void prim(Graph *graph) {
int lowcost[MAX_VERTEX_NUM], closest[MAX_VERTEX_NUM], mst[MAX_VERTEX_NUM];
for (int i = 0; i < graph->vexNum; i++) {
lowcost[i] = graph->arcs[0][i];
closest[i] = 0;
mst[i] = -1;
}
mst[0] = 0;
for (int i = 1; i < graph->vexNum; i++) {
int minCost = INF, k = -1;
for (int j = 0; j < graph->vexNum; j++) {
if (mst[j] == -1 && lowcost[j] < minCost) {
minCost = lowcost[j];
k = j;
}
}
if (k != -1) {
mst[k] = closest[k];
printf("(%d, %d) ", mst[k], k);
for (int j = 0; j < graph->vexNum; j++) {
if (graph->arcs[k][j] < lowcost[j]) {
lowcost[j] = graph->arcs[k][j];
closest[j] = k;
}
}
}
}
}
int main() {
Graph graph;
initGraph(&graph);
printf("深度优先遍历结果:\n");
bool visited[MAX_VERTEX_NUM] = {false};
for (int i = 0; i < graph.vexNum; i++) {
if (!visited[i]) {
dfs(&graph, i, visited);
}
}
printf("\n");
printf("广度优先遍历结果:\n");
for (int i = 0; i < graph.vexNum; i++) {
visited[i] = false;
}
for (int i = 0; i < graph.vexNum; i++) {
if (!visited[i]) {
bfs(&graph, i, visited);
}
}
printf("\n");
printf("最小生成树结果:\n");
prim(&graph);
printf("\n");
return 0;
}
```
希望这个程序可以帮到你!
阅读全文