生成最小树(普里姆算法)
Posted 不二小杰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生成最小树(普里姆算法)相关的知识,希望对你有一定的参考价值。
普利姆算法生成最小树,
当两个节点之间没有边时,权值为65535,结点与自身之间为0.。。。
#define MAXSIZE 10 typedef struct Graph { int table[MAXSIZE][MAXSIZE]; int num; }Graph; void createTable(Graph *graph); void printTable(Graph *graph); void prim(Graph *graph); int main(int argc, char *argv[]) { Graph graph; createTable(&graph); printTable(&graph); prim(&graph); return 0; } void prim(Graph *graph) { int num = graph->num; int pre[num]; int weight[num]; int i, j,min, k; j = 0; for(i=0; i<num-1; i++) { pre[i] = 0; weight[i] =( graph->table)[j][i]; } for(i=0; i<num; i++) { min = 65535; for(j=0;j<num; j++) { if(weight[j] != 0 && weight[j] < min) { min = weight[j]; k = j; } } printf("(%d, %d) ", pre[k], k); weight[k] = 0; for(j=0; j<num; j++) { if(weight[j] != 0 && (graph->table)[k][j] < weight[j] ) { weight[j] = (graph->table)[k][j]; pre[j] = k; } } } } void createTable(Graph *graph) { int i, j, temp; printf("输入节点数:"); scanf("%d", &(graph->num)); for(i=0; i<graph->num; i++) { for(j=0; j<graph->num; j++) { scanf("%d", &temp); if(temp == ‘ ‘) { j --; }else { (graph->table)[i][j] = temp; } } getchar(); } } void printTable(Graph *graph) { int i,j; for(i=0; i<graph->num; i++) { for(j=0; j<graph->num; j++) { printf("%d ", (graph->table)[i][j]); } printf("\n"); } }
以上是关于生成最小树(普里姆算法)的主要内容,如果未能解决你的问题,请参考以下文章