# 【你该懂一点Javascript算法系列】之单源最短路径 - Dijkstra算法

## Javascript算法系列 - 单源最短路径 - Dijkstra算法

ps: Dijkstra算法是一种贪心算法

``````let graph = [[0,2,4,0,0,0],
[0,0,1,4,2,0],
[0,0,0,0,3,0],
[0,0,0,0,0,2],
[0,0,0,3,0,2],
[0,0,0,0,0,0]]``````

ps: 邻接矩阵的意思是： 用一个二数组表示个顶点间的关系，来确定各顶点间的关系，因为图为有向图，所以上图的邻接矩阵如上

``````let index = 'ABCDEF'
let INF = Number.MAX_SAFE_INTEGER //1

function dijkstra(src) {
let dist = [],//2
visited = [],//3
length = graph.length//4

for (let i = 0; i < length; i++) {
dist[i] = INF
visited[i] = false
}//5
dist[src] = 0

for (let i = 0; i < length - 1; i++) {
let u = minDistance(dist, visited)
visited[u] = true

for (let v = 0; v < length; v++) {
if (!visited[v] && dist[u] !== INF && graph[u][v] > 0 && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v]
}
}
}

return dist
}

function minDistance(dist, visited) {
let min = INF,
minIndex = -1

for (let v = 0; v < dist.length; v++) {
if (visited[v] === false && dist[v] <= min) {
min = dist[v]
minIndex = v
}
}

return minIndex
}``````

1.初始化数据

``````for (let i = 0; i < length; i++) {
dist[i] = INF
visited[i] = false
}//5
dist[src] = 0``````

2.过程解析

``````//顶点探索函数
for (let i = 0; i < length - 1; i++) {
let u = minDistance(dist, visited)
visited[u] = true

for (let v = 0; v < length; v++) {
if (!visited[v] && dist[u] !== INF && graph[u][v] > 0 && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v]
}
}
}``````
``````//寻找最短路径函数
function minDistance(dist, visited) {
let min = INF,
minIndex = -1

for (let v = 0; v < dist.length; v++) {
if (visited[v] === false && dist[v] <= min) {
min = dist[v]
minIndex = v
}
}

return minIndex
}``````

``````visited -> [ true, false, false, false, false, false ]
dist -> [ 0, 2, 4, 9007199254740991, 9007199254740991, 9007199254740991 ]``````

A-C距离为A-B + B-C = 3小于直接到C的距离4 所以更新A-C最短距离

``````visited -> [ true, true, false, false, false, false ]
dist -> [ 0, 2, 3, 6, 4, 9007199254740991 ]``````

dist -> [ 0, 2, 3, 6, 4, 9007199254740991 ]
visited -> [ true, true, true, false, true, false ]
dist -> [ 0, 2, 3, 6, 4, 6 ]
visited -> [ true, true, true, false, true, true ]
[ 0, 2, 3, 6, 4, 6 ]

[ 0, 2, 3, 6, 4, 6 ]