首页 > 搜索 > 最短路径贪心算法复杂度,贪心算法之Dijkstra算法, 求单源最短路径-xiaozhu2007

最短路径贪心算法复杂度,贪心算法之Dijkstra算法, 求单源最短路径-xiaozhu2007

互联网 2020-10-30 00:04:20
在线算命,八字测算命理

#include stdio.h>

#define maxnodenum 100#define maxedgenum 100#define MAX_VALUE200int matrix[maxnodenum][maxnodenum];int nodes[maxnodenum], dist[maxnodenum], prev[maxnodenum];int nodenum, edgenum;static void matrix_init(void);static void dijkstra(int v);static void print_dijkstra(int v, int e);int main(int argc, char **argv){ int v, e;

        matrix_init();        printf("Input source node: ");        scanf("%d", &v);        getchar();        dijkstra(v);        printf("Input end node: ");        scanf("%d", &e);        getchar();        print_dijkstra(v, e);        return(0);}

static void matrix_init(void){        int i, j, row, col, weight;

        printf("Input nodenum and edgenum:\n");        scanf("%d %d", &nodenum, &edgenum);        getchar();

        for(i = 1; i = nodenum; i++){                for(j = 1; j = nodenum; j++){                        matrix[i][j] = MAX_VALUE;                }        }

        printf("Input all edges:\n");        for(i = 0; iedgenum; i++){                scanf("%d %d %d", &row, &col, &weight);                getchar();                matrix[row][col] = weight;        }}

static void dijkstra(int v){        int i, j, u, temp, newdist;

        for(i = 1; i = nodenum; i++){                dist[i] = matrix[v][i];                if((dist[i] == MAX_VALUE)){                        prev[i] = 0;                }                else{                        prev[i] = v;                }        }

        nodes[v] = 1;        for(i = 1; inodenum; i++){                temp = MAX_VALUE;                u = v;                for(j = 1; j = nodenum; j++){                        if((!nodes[j]) && (dist[j]temp)){                                temp = dist[j];                                u = j;                        }                }                nodes[u] = 1;                for(j = 1; j = nodenum; j++){                        if((!nodes[j]) && (matrix[u][j]MAX_VALUE)){                                newdist = matrix[u][j] + dist[u];                                if(newdistdist[j]){                                        dist[j] = newdist;                                        prev[j] = u;                                }                        }                }        }}

static void print_dijkstra(int v, int e){        int i;

        printf("The shortest path from node %d to node %d is: ", v, e);        printf("%d", e);        for(i = e; i != v; i = prev[i]){                printf(", prev[i]);        }        printf("\n");}

免责声明:非本网注明原创的信息,皆为程序自动获取互联网,目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责;如此页面有侵犯到您的权益,请给站长发送邮件,并提供相关证明(版权证明、身份证正反面、侵权链接),站长将在收到邮件12小时内删除。

相关阅读

一周热门

查看更多