我的程序有以下变量输入数组,例如: [AB3,EC10]
它可以是任意长度,第一秒字符分别是路径的起点和终点。以下数字是第一个和第二个字符(节点)之间的距离。
如果你只能逐步从一个节点前进到另一个节点,那么我如何计算从一个点到另一个点的最短路径(从A到D,你必须去AB,BC,CD, ED)和节点之间的距离是可变的吗?
const routesInfo = ["AB5", "BC4", "CD8", "DC8", "DE6", "AD5", "CE2", "EB3", "AE7"]
const stop1 = 'A',
stop2 = 'B',
stop3 = 'C',
stop4 = '',
stop5 = ''
var trip1dist = 0,
trip2dist = 0,
trip3dist = 0,
trip4dist = 0,
dist = 0
// for 3 stations
if (stop1 && stop2 && stop3 && (!stop4) && (!stop5)) {
var foundFirst = false,
foundSecond = false
for (var i = 0; i<routesInfo.length;i++) {
var origin = routesInfo[i].charAt(0),
destination = routesInfo[i].charAt(1)
if (origin == stop1 && destination == stop2) {
distance = routesInfo[i].charAt(2)
trip1dist = distance
foundFirst = true
}
if (origin == stop2 && destination == stop3) {
distance = routesInfo[i].charAt(2)
trip2dist = distance
foundSecond = true
}
}
// REFACTOR CHECKING FOR IMPOSSIBLE ROUTE
if (foundFirst && !foundSecond) {
console.log(null)
}
if (!foundFirst && foundSecond) {
console.log(null)
}
if (!foundFirst && !foundSecond) {
console.log(null)
}
var total = Number(trip1dist) + Number(trip2dist)
console.log('The distance of the trip was: '+total)
}