在javascript中实现dijkstra算法的错误

时间:2012-06-29 19:53:45

标签: javascript algorithm dijkstra

我根据wiki中给出的伪代码制作了这段代码。还是有一些错误。请帮我编码并告诉我如何改进它我从几小时开始尝试! 我已将我知道的那条线标记为错误。和休息我不知道我错在哪里

  var graph = [{
        from: [1, 2, 3, 4],
        to: [3, 3, 5, 6]
    }];
    var shortestpath = function (graph, source) {
            for (i in graph) {
                dist[i] = infinty;
                prev[i] = undefined;
            }
            dist[source] = 0;
            var q = [];
            q.push(graph.value);
            while (q != 0) {
               var min_distance = infinity;
var u = null;

for (var i in dist) {
   if (dist[i] < min_distance) {
      u = i;
      min_distance = dist[u];
   }
}
                if (dist[u] = infinity) {
                    break;
                }
                q.pop(u);
                for (v in u) {
                    var alt = dist[u] + dist_between(u, v);
                    if (alt < dist[v]) {
                        dist[v] = alt;
                        previous[v] = u;
                        q.sort(v);
                    }
                }
            }
            return dist;
        }
    }

1 个答案:

答案 0 :(得分:0)

根据Dijkstra's algorithm pseudocodeu不应该是列表,而是一个简单的int,它保存Q中距离较小的顶点的索引

如果你想要距离最小的顶点,你可以迭代顶点数组,跟踪到目前为止找到的最小距离,并将u分配给具有此ditance的顶点。 / p>

var min_distance = infinity;
var u = null;

for (var i in dist) {
   if (dist[i] < min_distance) {
      u = i;
      min_distance = dist[u];
   }
}