function Graph(matrixOriginal = [], vertexName = []) {
this.Dijkstra = function (start = 0) {
let matrix = matrixOriginal;
const rows = matrix.length,//rows和cols一样,其实就是顶点个数
cols = matrix[0].length;
var parent = [];//记录(探索每个顶点时的)上一个顶点
if (rows !== cols || start >= rows) {
return new Error("邻接矩阵错误或者源点错误");
}
//重置个边的权重
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if ( i!=j && matrix[i][j] === 0) {
matrix[i][j] = Infinity;
}
}
}
//初始化distance,记录起点到各个顶点的最小距离,key为顶点,value为距离,起点距离为0
const distance = new Array(rows).fill(Infinity);
distance[start] = 0;
for (let i = 0; i < rows; i++) {
//达到不了的顶点不能作为中转跳点
if (distance[i] < Infinity) {
for (let j = 0; j < cols; j++) {
//比如通过比较distance[i] + matrix[i][j]和distance[j]的大小来决定是否更新distance[j]。
if (distance[i] + matrix[i][j] < distance[j]) {
distance[j] = distance[i] + matrix[i][j];
parent[j] = i;
}
}
}
}
return {
distance: distance,
parent: parent
};
};
}
var matrix = [
// A B C D E F
// 0 1 2 3 4 5
/*A 0*/[0, 2, 4, 0, 0, 0],
/*B 1*/[0, 0, 1, 4, 2, 0],
/*C 2*/[0, 0, 0, 0, 3, 0],
/*D 3*/[0, 0, 0, 0, 0, 2],
/*E 4*/[0, 0, 0, 3, 0, 2],
/*F 5*/[0, 0, 0, 0, 0, 0]
];
var vertexName = ['A', 'B', 'C', 'D', 'E', 'F'];
var g = new Graph(matrix, vertexName);
var r = g.Dijkstra(0);
console.log(r);
// A B C D E F
// 0 1 2 3 4 5
/*A 0*/[0, 2, 4, 0, 0, 0],
/*B 1*/[0, 0, 1, 4, 2, 0],
/*C 2*/[0, 0, 0, 0, 3, 0],
/*D 3*/[0, 0, 0, 0, 0, 2],
/*E 4*/[0, 0, 0, 3, 0, 2],
/*F 5*/[0, 0, 0, 0, 0, 0]
重置个边的权重
原始的图,进行路径初始化,将[没有连接的边的权重]设置为无穷大。
// A B C D E F
// 0 1 2 3 4 5
/*A 0*/[ 0, 2, 4, Infinity, Infinity, Infinity],
/*B 1*/[Infinity, 0, 1, 4, 2, 0],
/*C 2*/[Infinity, Infinity, 0, Infinity, 3, Infinity],
/*D 3*/[Infinity, Infinity, Infinity, 0, Infinity, 2],
/*E 4*/[Infinity, Infinity, Infinity, 3, 0, 2],
/*F 5*/[Infinity, Infinity, Infinity, Infinity, Infinity, 0]
运行结果
顶点 | 起点与该顶点的距离(distance) | 到达该顶点的上一个顶点(parent) |
---|---|---|
A 0 | 0 | |
B 1 | 2 | A 0 |
C 2 | 3 | B 1 |
D 3 | 6 | B 1 |
E 4 | 4 | B 1 |
F 5 | 6 | E 4 |
参考文献:
[1] [巴西]Loiane Groner. 学习JavaScript数据结构与算法(第2版)[M]. 人民邮电出版社,2017.
[2] [日本]石田保辉,宫崎修一. 我的第一本算法书[M]. 人民邮电出版社,2018.
[3] 最短路径算法——Dijkstra算法的JS实现[EB/OL]. https://blog.csdn.net/sinat_36521655/article/details/82085936