在JavaScript中查找对象数组中的最短路径

时间:2017-08-17 10:07:50

标签: javascript arrays data-structures

我有像

这样的对象数组
const obs = [
    { from: "A", to: "C", dis: 5},
    { from: "A", to: "D", dis: 4},
    { from: "D", to: "C", dis: 8},
    { from: "C", to: "B", dis: 9},
    { from: "B", to: "D", dis: 17},
]

现在我必须找到从A到B的最短路径dis。 所以我创建了2d数组的距离矩阵

findUniqueEndPoints() {

        let _endPoints = []
        obs.forEach(e => {
            if (!_endPoints.includes(e.from)) {
                _endPoints.push(e.from)
            }
            if (!_endPoints.includes(e.to)) {
                _endPoints.push(e.to)
            }

        })
        return _endPoints
    }

    this.endPoints = this.findUniqueEndPoints()
    let _matrix = []
    this.endPoints.forEach((e, i) => {
        //const valus = obs.map(o => o.from === e ? o.dis : null)
       _matrix[i] = this.endPoints.map(() => 0)
   })

   obs.forEach(e => {
       _matrix[this.endPoints.indexOf(e.from)][this.endPoints.indexOf(e.to)] = e.dis
   })
   console.log(_matrix)
  // logs
  //[[0, 5, 4, 0][0, 0, 0, 9][0, 8, 0, 0][0, 0, 17, 0]]

1 个答案:

答案 0 :(得分:0)

使用djikstra类似于路径寻找的逻辑,构建每个点的步骤映射,同时跟踪它的路径:



os_zalloc()