Dijkstra模板求單源點最短路徑

#include <iostream>
using namespace std;

const int maxnum = 100;
const int maxint = 999999;

// 各數組都從下標1開始
int dist[maxnum];     // 表示當前點到源點的最短路徑長度
int prev[maxnum];     // 記錄當前點的前一個結點
int c[maxnum][maxnum];   // 記錄圖的兩點間路徑長度
int n, line;             // 圖的結點數和路徑數

// n -- n nodes
// v -- the source node
// dist[] -- the distance from the ith node to the source node
// prev[] -- the previous node of the ith node
// c[][] -- every two nodes' distance
void Dijkstra(int n, int v, int *dist, int *prev, int c[maxnum][maxnum])
{
    bool s[maxnum];    // 判斷是否已存入該點到S集合中
    for(int i=1; i<=n; ++i)
    {
        dist[i] = c[v][i];
        s[i] = 0;     // 初始都未用過該點
        if(dist[i] == maxint)
            prev[i] = 0;
        else
            prev[i]     = v;
    }
    dist[v] = 0;
    s[v] = 1;

    // 依次將未放入S集合的結點中,取dist[]最小值的結點,放入結合S中
    // 一旦S包含了所有V中頂點,dist就記錄了從源點到所有其他頂點之間的最短路徑長度
         // 注意是從第二個節點開始,第一個爲源點
    for(int i=2; i<=n; ++i)
    {
        int tmp = maxint;
        int u = v;
        // 找出當前未使用的點j的dist[j]最小值
        for(int j=1; j<=n; ++j)
            if((!s[j]) && dist[j]<tmp)
            {
                u = j;              // u保存當前鄰接點中距離最小的點的號碼
                tmp = dist[j];
            }
        s[u] = 1;    // 表示u點已存入S集合中

        // 更新dist
        for(int j=1; j<=n; ++j)
            if((!s[j]) && c[u][j]<maxint)
            {
                int newdist = dist[u] + c[u][j];
                if(newdist < dist[j])
                {
                    dist[j] = newdist;
                    prev[j] = u;
                }
            }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章