生成最小树(普里姆算法)
普利姆算法生成最小树,
当两个节点之间没有边时,权值为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"); } }