javascript手撕Floyd-Warshall算法(带路径)

folyd-warshall是求最短路径的算法,它的功能比较强大,可以求任意两点的最短距离。
它是一种动态规划的算法,floyd-warshall与dijkstra算法有着很大的区别:
1.结果上,dijkstra是求得一点到任一点的最短距离(一维数组),而floyd-warshall的结果是任意两点之间的最短距离(二维数组)。
2.思想上,dijkstra是从给定源点开始,比较源点到当前点所有可达的点的距离,找出最小的距离,这个最小的距离上的最后一个点,就是源点到最后一个点的最短距离,然后再把最后一个点作为当前点进行迭代,每次都要找最短距离,体现了该算法的贪心思想;floyd-warshall是动态地更新任意两点之间的最短距离,怎么才能更新呢,那就要找到第三个点,比如说要更新AB两点之间的最短距离,那就拿第三个点P,看看是否AP的距离+PB的距离是否小于AB的距离,如果小于,则更新AB的距离,这采用了动态规划的思想。

以下是floyd-warshall算法的js代码

const initDistanceAndPath = (graph) => {
  const n = graph.length;
  const distance = [];
  const path = [];
  for (let i = 0; i < n; i++) {
    distance[i] = [];
    path[i] = [];
    for (let j = 0; j < n; j++) {
      if (i === j) {
        distance[i][j] = 0;
        path[i][j] = [i];
      } else if (graph[i][j] === 0) {
        distance[i][j] = Infinity;
        path[i][j] = [];
      } else {
        distance[i][j] = graph[i][j];
        path[i][j] = [i, j];
      }
    }
  }
  return { distance, path };
}

const floydWarshall = (graph) => {
  const { distance, path } = initDistanceAndPath(graph);
  const n = graph.length;
  for (let k = 0; k < n; k++) {
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        if (distance[i][j] > distance[i][k] + distance[k][j]) {
          distance[i][j] = distance[i][k] + distance[k][j];
          path[i][j] = path[i][k].concat(path[k][j][1]);
        }
      }
    }
  }
  return { distance, path };
}
const graph = [[0, 2, 4, 0, 0, 0], [0, 0, 2, 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]];

console.log(floydWarshall(graph));
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值