每个城镇的金额是未知的,所以最好的路线是从一个城镇到下一个城镇的最短路线。
如果我要使用递归在 Javascript 中对此进行编程,我会这样做:
http://jsfiddle.net/rd13/ShL9X/5/
c = ['london', 'manchester', 'liverpool']; //Cities
t = {
'liverpool': {
'manchester': 130,
'london': 260
},
'london': {
'manchester': 250,
'liverpool': 260
},
'manchester': {
'london': 250,
'liverpool': 130
}
} //Time between cities
cn = 'london'; //Current city
var shortestDistance = 500,
allottedTime = 300,
next_city,
time = 0,
totalTime = 0,
path = [cn];
optimal = function (cn) {
for (i in t[cn]) {
//So as not to visit cities that we have already visited
if(path.indexOf(i)===-1) {
next_city = t[cn][i] < shortestDistance ? i : next_city;
shortestDistance = t[cn][i];
totalTime = Math.min(t[cn][i] , shortestDistance);
}
}
time += totalTime;
path.push(next_city);
if(time > allottedTime){
document.write("The most optimal route between cities is: " + path);
} else {
optimal(next_city);
}
}
optimal(cn);
抱歉,对算法没有帮助,这是从编程的角度来看的,因为我认为这是一个有趣的挑战。以上不是最佳思想。