1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| function dijkstra(path, index) { let m = path && path.length; let n = m && path[0].length;
if (m && n && m === n && index < n) { let dis = JSON.parse(JSON.stringify(path[index]));
let flag = []; for (let i = 0; i < n; i++) { flag.push(false) } flag[index] = true;
let min, minIndex; dis[index].way = [dis[index].shop, dis[index].shop] for (let i = 0; i < n; i++) { min = Infinity; for (let j = 0; j < n; j++) { if (!flag[j] && dis[j].weight < min) { min = dis[j].weight; minIndex = j; } } flag[minIndex] = true; if (dis[minIndex].way == undefined) dis[minIndex].way = [dis[index].shop, dis[minIndex].shop] for (let k = 0; k < n; k++) { if (dis[k].way == undefined) dis[k].way = dis[k].way = [dis[index].shop, dis[k].shop] if (path[minIndex][k].weight < Infinity) { if (dis[k].weight > dis[minIndex].weight + path[minIndex][k].weight) { dis[k].weight = dis[minIndex].weight + path[minIndex][k].weight; dis[k].way = [...dis[minIndex].way, path[minIndex][k].shop] } } } } return dis; } else { throw new Error("数据有误") } }
let path = [ [0, 1, 9, 7, 1], [1, 0, 3, 6, 8], [9, 3, 0, 2, 5], [7, 6, 2, 0, 2], [1, 8, 5, 2, 0] ]
console.log("source", path) const PATHS = [] const Arr = ["A", "B", "C", "D", "E"] for (let index = 0; index < path.length; index++) { PATHS[index] = path[index].map((value, index) => { return { weight: value, shop: Arr[index] } }) }
let res = [] let log = '' for (let index = 0; index < PATHS.length; index++) { let result = dijkstra(PATHS, index) res[index] = result.map(value => value.weight) log += `start shop: ${result[index].shop}\n` result.forEach(value => log += `end: ${value.shop} weight: ${value.weight} path: ${value.way.toString().replace(/,/g, "-->")}\n`) } console.log('result', res) console.log(log)
|