码迷,mamicode.com
首页 > 编程语言 > 详细

生成最小树(普里姆算法)

时间:2017-09-07 23:02:02      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:最小   普里姆算法   creat   pre   char   amp   blog   printf   efi   

普利姆算法生成最小树,

当两个节点之间没有边时,权值为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");
    }
 }

 

生成最小树(普里姆算法)

标签:最小   普里姆算法   creat   pre   char   amp   blog   printf   efi   

原文地址:http://www.cnblogs.com/buerr/p/7492078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!