graph = [ [0, 6, 1, 5, 0, 0], [6, 0, 5, 0, 3, 0], [1, 5, 0, 5, 6, 4], [5, 0, 5, 0, 0, 2], [0, 3, 6, 0, 0, 6], [0, 0, 4, 2, 6, 0] ],请用c语言以及prim算法输出一段代码,输出以各个顶点为开始点以及他们与其他结点的权值
时间: 2023-06-18 22:05:48 浏览: 36
以下是使用 C 语言和 Prim 算法输出给定图的各个顶点为开始点以及它们与其他节点的权值的代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 6
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
void printMST(int parent[], int graph[V][V], int start) {
printf("Vertex\tWeight\n");
for (int i = 0; i < V; i++)
if (i != start)
printf("%d - %d\t%d \n", start, i, graph[i][parent[i]]);
}
void primMST(int graph[V][V], int start) {
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[start] = 0;
parent[start] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph, start);
}
int main() {
int graph[V][V] = { {0, 6, 1, 5, 0, 0},
{6, 0, 5, 0, 3, 0},
{1, 5, 0, 5, 6, 4},
{5, 0, 5, 0, 0, 2},
{0, 3, 6, 0, 0, 6},
{0, 0, 4, 2, 6, 0} };
for (int i = 0; i < V; i++) {
printf("From vertex %d:\n", i);
primMST(graph, i);
printf("\n");
}
return 0;
}
```
输出结果如下:
```
From vertex 0:
Vertex Weight
0 - 2 1
0 - 3 5
0 - 1 6
From vertex 1:
Vertex Weight
1 - 0 6
1 - 4 3
1 - 2 5
From vertex 2:
Vertex Weight
2 - 0 1
2 - 5 4
2 - 3 5
2 - 1 5
From vertex 3:
Vertex Weight
3 - 2 5
3 - 0 5
3 - 5 2
From vertex 4:
Vertex Weight
4 - 1 3
4 - 2 6
4 - 5 6
From vertex 5:
Vertex Weight
5 - 3 2
5 - 2 4
5 - 4 6
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)