JavaScript与Dijkstra 最短路算法(两种实现)

阅读前提: 了解Dijkstra算法的逻辑思想

 前言:Dijkstra算法通常用来计算单向图两个顶点之间的最短距离,需求分为:需要追踪路径不需要追踪路径,本次内容将分享两种需求的简单实现

 

1.不需要追踪路径(实现思路:邻接矩阵)

//邻接矩阵
const matrix= [
  [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]
];


//遍历出指定start到各个顶点最小距离
function Dijkstra(matrix,start = 0){
	const rows = matrix.length, cols = matrix[0].length;
	if(rows !== cols || start >=rows) { return new Error("零阶矩阵错误/起点错误")}
	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++){
				if(matrix[i][j] + distance[i] < distance[j]){
					distance[j] = matrix[i][j] + distance[i];
				}
			}
		}
	}
	console.log(distance);
}
Dijkstra(matrix);

2.需要追踪路径(实现思路:路径表 , 可参考图解算法第七章)

const path = {
	"乐谱":{ "海报":0, "黑胶唱片":5},
	"海报": { "架子鼓":35,"低音吉他":30},
	"黑胶唱片": { "低音吉他":15,"架子鼓":20},
	"架子鼓":{ "钢琴":10 },
	"低音吉他": {"钢琴":20},
	"钢琴":{}
}

function dijkstra(path){
	//获取节点列表
	let nodes = Object.keys(path);
	//存储数据
	let table = new Array();
	for(let parent of nodes){
		//遍历所有子路径
		for(let child of Object.keys(path[parent])){
			//查找到达parent节点的花费
			let ancestorsCost = table.filter(n=>n.node == parent);
			//定义当前子路径
			let currItem = {
				parent:parent,
				node: child,
				cost:ancestorsCost[0] ? ancestorsCost[0].cost + path[parent][child] : path[parent][child]
			};
			//处理同样到达当前节点node的路径
			let flag = true; 
			table.forEach((e,index)=>{
				//存在node数据一样,并且以往开销更大,更新路径,不需要新增路径
				if(e.node == child && e.cost > currItem.cost){
					e.parent = currItem.parent;
					e.cost = currItem.cost;
					flag = false;
				} else if (e.node == child && e.cost < currItem.cost){
					//如果存在,但是以往路径开销更小,不需要新增路径
					flag = false;
				}
			})
			//没有同样到达当前节点node的路径,新增路径
			if(flag){
				table.push(currItem);
			}		
		}
	}
	console.log(table);
}
dijkstra(path);

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值