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

最短路径(迪杰斯特拉算法)

时间:2017-09-09 00:03:05      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:str   amp   size   相同   lib   算法   log   ++   []   

假定条件和上一篇相同。。。

其实算法思路和上一篇也相同,均为贪心算法。。。

/*
*  author: buer
*  github: buer0.github.com
*/

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10

typedef struct Graph
{
    int table[MAXSIZE][MAXSIZE];
    int num;
}Graph;

void createTable(Graph *graph);
void printTable(Graph *graph); 
void shortest(Graph *graph, int start, int end);
 
int main(int argc, char *argv[])
{
    Graph graph;
    
    
    createTable(&graph);
    
    printTable(&graph);
    
    shortest(&graph, 0,1); 
    return 0;
}

void shortest(Graph *graph, int start, int end) 
{
    int num = graph->num;
    int pre[num];
    int weight[num];
    int final[num];
    int i, j,min, k;
    
    for(i=0; i<num; i++)
    {
        pre[i] = 0;
        weight[i] =( graph->table)[start][i];
        final[i] = 0;
    }
    
    final[start] = 1;
    
    for(i=1; i<num; i++)
    {
        min = 65535;
        
        for(j=0;j<num; j++)
        {
            if((!final[j]) && weight[j] != 0 && weight[j] < min)
            {
                min = weight[j];
                k = j;
            }
        }
        
        final[k] = 1;
        
        if(k == end)
        {
            break;
        }
        
        for(j=0; j<num; j++)
        {
            if((!final[j]) && ((min+(graph->table)[k][j] )< weight[j]) )
            {
                weight[j] = min+(graph->table)[k][j];
                pre[j] = k;
            }
        }
    }
    
    for(i=0; i<num ; i++)
    {
        printf("%d ", weight[i]);
    }
    
}

void createTable(Graph *graph)
{
    int i, j, temp;
    printf("输入节点数:");
    scanf("%d", &(graph->num));
    
    for(i=0; i<graph->num; i++)
    {
        printf("第 %d 行:", i+1);
        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;
    printf("\n");
    for(i=0; i<graph->num; i++)
    {
        for(j=0; j<graph->num; j++)
        {
            printf("%d ", (graph->table)[i][j]);
        }
        printf("\n");
    }
 }

 

最短路径(迪杰斯特拉算法)

标签:str   amp   size   相同   lib   算法   log   ++   []   

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

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