最短路径算法(D算法)

2017-05-14  本文已影响0人  Mr_码客

解决最短路径算法的D算法,是一个解决从点到点之间最短路径的问题,看下面这张图:


var INFINITE = 65535;
var NODE_NUMBER = 6;

var weight =
    [
        [0, 7, 9, INFINITE, INFINITE, 14],
        [7, 0, 10, 15, INFINITE, INFINITE],
        [9, 10, 0, 11, INFINITE, 2],
        [INFINITE, 15, 11, INFINITE, 6, INFINITE],
        [INFINITE, INFINITE, INFINITE, 6, 0, 9],
        [14, INFINITE, 2, INFINITE, 9, 0]
    ]

var dis = [0, 7, 9, INFINITE, INFINITE, 14];
var s = [1, 0, 0, 0, 0, 0];

for (i = 1; i < NODE_NUMBER; i++) {
    var minWeight = INFINITE;
    var v = 0;
    for (var j1 = 0; j1 <= NODE_NUMBER; j1++) {
        if (![s[j1]] && dis[j1] < minWeight) {
            v = j1;
            minWeight = dis[j1];
        }
    }

    s[v] = 1;
    for (var j2 = 0; j2 < NODE_NUMBER; j2++) {
        if (!(s[j2]) && weight[v][j2] < INFINITE) {
            if ((dis[v] + weight[v][j2] < dis[j2])) {
                dis[j2] = dis[v] + weight[v][j2];
            }
        }
    }
}

console.log(dis);
上一篇下一篇

猜你喜欢

热点阅读