Prim 算法屬於貪心算法。web
#include <stdio.h> #define VERTEXNUM 7 #define INF 10000 typedef struct Graph { int vertex[VERTEXNUM]; int edge[VERTEXNUM][VERTEXNUM]; } Graph; void initGraph(Graph* G) { int i, j; int init[][3] = {{1, 2, 10}, {1, 3, 8}, {1, 6, 20}, {2, 3, 3}, {2, 5, 30}, {3, 4, 18}, {3, 6, 7}, {4, 5, 2}, {6, 7, 1}}; for (i = 0; i < VERTEXNUM; i++) { G->vertex[i] = 'a' + i; for (j = 0; j < VERTEXNUM; j++) { G->edge[i][j] = INF; } } for (i = 0; i < 9; i++) { G->edge[init[i][0] - 1][init[i][1] - 1] = init[i][2]; G->edge[init[i][1] - 1][init[i][0] - 1] = init[i][2]; } } void prim(Graph* G) { int parent[VERTEXNUM]; int selected[VERTEXNUM]; int nearest[VERTEXNUM]; int i, j, k, lastVer, min; for (i = 0; i < VERTEXNUM; i++) { parent[i] = -1; selected[i] = 0; nearest[i] = INF; } lastVer = 0; // selected[0] = 1; for (i = 0; i < VERTEXNUM; i++) { if (G->edge[0][i] < INF) { parent[i] = 0; nearest[i] = G->edge[0][i]; } } for (i = 1; i < VERTEXNUM; i++) { min = INF; if (selected[lastVer] == 1) continue; selected[lastVer] = 1; for (j = 0; j < VERTEXNUM; j++) { if (G->edge[lastVer][j] < nearest[j]) { parent[j] = lastVer; nearest[j] = G->edge[lastVer][j]; } } for (j = 0; j < VERTEXNUM; j++) { if (selected[j] != 1 && nearest[j] < min) { min = nearest[j]; lastVer = j; } } printf("lastVer: %d\n", lastVer); } } int main () { Graph G; initGraph(&G); prim(&G); return 0; }