html
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
</style>
</head>
<body>
<div id="box1"></div>
</body>
<script type="text/javascript">
// dijkstra 函数
// 它接受一个图和一个起始节点作为参数,并返回一个包含最短距离和前驱节点的对象。
function dijkstra(graph, start) {
const distances = {};
const visited = {};
const previous = {};
const queue = [];
for (let vertex in graph) {
distances[vertex] = Infinity;
previous[vertex] = null;
queue.push(vertex);
}
distances[start] = 0;
while (queue.length) {
let current = null;
for (let vertex of queue) {
if (!current || distances[vertex] < distances[current]) {
current = vertex;
}
}
queue.splice(queue.indexOf(current), 1);
visited[current] = true;
for (let neighbor in graph[current]) {
let distance = graph[current][neighbor];
let totalDistance = distances[current] + distance;
if (totalDistance < distances[neighbor]) {
distances[neighbor] = totalDistance;
previous[neighbor] = current;
}
}
}
return { distances, previous };
}
const graph = {
A: { B: 5, C: 1 },
B: { A: 5, C: 2, D: 1 },
C: { A: 1, B: 2, D: 4, E: 8 },
D: { B: 1, C: 4, E: 3, F: 6 },
E: { C: 8, D: 3 },
F: { D: 6 }
};
// 上述代码中,我们定义了一个图,并使用 dijkstra 函数计算了从节点A到其他节点的最短距离和前驱节点。
// 最后,我们将结果打印到控制台上。
var startPoint = 'A';
var endPoint = 'F';
const { distances, previous } = dijkstra(graph, startPoint);
console.log(distances);
// A到其他节点的最短距离
// {
// A: 0,
// B: 5,
// C: 1,
// D: 6,
// E: 9,
// F: 12
// }
console.log(previous);
// A到其他节点的前驱结点:
// {
// A: null,
// B: 'C',
// C: 'A',
// D: 'B',
// E: 'D',
// F: 'D' A -> B -> D->F
// }
console.log("xxxxxxxxxxxxx");
// 打印出 startPoint 到 endPoint 的最短路径
function getPath( previous ){
var path=[];
var target = endPoint;
while( true ){
path.push( target );
var prev = previous[ target ];
console.log( prev + " --> " + target );
if( prev == startPoint ){
path.push( startPoint );
break;
}
target = prev;
}
path = path.reverse();
return path;
}
var path = getPath( previous );
console.log( path );
</script>
</html>