function dijkstra(data, source) { var dist = [], path = [], visit = []; var len = data.length; for (var i = 0; i < len; i++) { dist[i] = data[source][i]; path[i] = source; visit[i] = false; } dist[source] = 0; visit[source] = true; for (var i = 1; i < len; i++) { var min = {idx: -1, weight: Infinity}; for (var j = 0; j < len; j++) { if ( false === visit[j] && dist[j] < min.weight ) min = {idx: j, weight: dist[j]}; } visit[ min.idx ] = true; for (var k = 0; k < len; k++) { if ( false === visit[k] && min.weight + data[min.idx][k] < dist[k] ) { dist[k] = min.weight + data[min.idx][k]; path[k] = min.idx; } } } return [dist, path]; } var data = [ [0, 9, 2, Infinity, 6], [9, 0, 3, Infinity, Infinity], [2, 3, 0, 5, Infinity], [Infinity, Infinity, 5, 0, 1], [6, Infinity, Infinity, 1, 0] ]; console.log( dijkstra(data, 1) );
|