Dijkstra算法

Dijkstra算法测试

#include <iostream>
#include <vector>
using namespace std;

#define INF 99999999

vector<int> Dijkstra(vector<vector<int>>& graph, int start){
    int n = graph.size();
    //初始化
    vector<int> visit(n, 0);
    vector<int> dist(n, 0);
    for(int i = 0; i < n; i++){
        dist[i] = graph[start][i];
    }
    visit[start] = 1;

    //更新最短路径的循环,循环n次
    for(int i = 0; i < n; i++){
        int min_dist = INF;
        int middle = 0;

        //寻找未被访问的顶点中距离起始顶点的最短距离
        for(int j = 0; j < n; j++){
            if(visit[j] == 0 && min_dist > dist[j]){
                min_dist = dist[j];
                middle = j; //记录下中间节点
            }
        }
        //以middle为中间节点,更新起始点到其他各点的最小距离
        for(int j = 0; j < n; j++){
            if(visit[j] == 0 && dist[j] > dist[middle] + graph[middle][j]){
                dist[j] = dist[middle] + graph[middle][j];
            }
        }
        //设置中间节点已经被访问
        visit[middle] = 1;
    }
    return dist;
}

int main() {
    vector<vector<int>> graph;
    //0 北京
    //1 天津
    //2 郑州
    //3 济南
    //4 长沙
    //5 海南
    int n = 6;
    for(int i = 0; i < n; i++){
        graph.push_back(vector<int>());
        for(int j = 0; j < n; j++){
            graph[i].push_back(INF);
        }
        graph[i][i] = 0;
    }

    graph[0][1] = 100;
    graph[1][0] = 100;

    graph[0][2] = 1200;
    graph[2][0] = 1200;

    graph[1][2] = 900;
    graph[2][1] = 900;

    graph[1][3] = 300;
    graph[3][1] = 300;

    graph[2][3] = 400;
    graph[3][2] = 400;

    graph[2][4] = 500;
    graph[4][2] = 500;

    graph[3][4] = 1300;
    graph[4][3] = 1300;

    graph[3][5] = 1400;
    graph[5][3] = 1400;

    graph[4][5] = 1500;
    graph[5][4] = 1500;

    vector<int> dist = Dijkstra(graph, 0);
    printf("From 北京 min dist : \n");
    for(int i = 0; i < n; i++){
        printf("dist[%d] = %d\n", i,dist[i]);
    }

    vector<int> dist2 = Dijkstra(graph, 2);
    printf("From 郑州 min dist : \n");
    for(int i = 0; i < n; i++){
        printf("dist2[%d] = %d\n", i,dist2[i]);
    }

    return 0;
}

参考:原理讲解

posted @ 2022-02-11 10:42  水水滴答  阅读(31)  评论(0编辑  收藏  举报