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

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

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

/*
*  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");
    }
 }

 

posted @ 2017-09-08 22:40  牛奶无花果  阅读(215)  评论(0编辑  收藏  举报