Javascript:189个字符
这是一种递归解决方案,可找到经历冒险的最短路径。
代码化的:
a=prompt().split('\\n');b=0;while(!(d=c(b++,1)));function c(e,f,i,g){if(e>0)for(i=0;h=a[i++];){g=h.split(' ');if(g[0]==f){if(g[1]==100)return h;if(j=c(e-1,g[1]))return g[0]+' '+j}}}alert(d)
要测试(警告:输入错误的无限循环!):
复制以下输入字符串之一(或使用类似的格式来选择自己的选择自己的冒险):
1 10\n10 5\n10 13\n5 12\n5 19\n13 15\n12 20\n15 100
15 2\n1 4\n2 12\n1 9\n3 1\n1 15\n9 3\n12 64\n4 10\n2 6\n80 100\n5
10\n6 24\n12 80\n6 150\n120 9\n150 120
将其粘贴到测试小提琴的提示中。
格式化和注释代码:
//Get Input from user
inputLines = prompt().split('\\n');
//Starting at 0, check for solutions with more moves
moves = 0;
while (!(solution = getSolution(moves++, 1)));
/**
* Recursive function that returns the moves string or nothing if no
* solution is available.
*
* @param numMoves - number of moves to check
* @param startPage - the starting page to check
* @param i - A counter. Only included to make this a local variable.
* @param line - The line being tested. Only included to make this a local variable.
*/
function getSolution(numMoves, startPage, i, line) {
//Only check for solutions if there are more than one moves left
if (numMoves > 0) {
//Iterate through all the lines
for (i=0; text = inputLines[i++];) {
line = text.split(' ');
//If the line's start page matches the current start page
if (line[0] == startPage) {
//If the goal page is the to page return the step
if (line[1] == 100) {
return text;
}
//If there is a solution in less moves from the to page, return that
if (partialSolution = getSolution(numMoves - 1, line[1])) {
return line[0] + ' ' + partialSolution;
}
}
}
}
}
//Output the solution
alert(solution);
要测试(警告:输入错误的无限循环!):
复制以下输入字符串之一(或使用类似的格式来选择自己的选择自己的冒险):
1 10\n10 5\n10 13\n5 12\n5 19\n13 15\n12 20\n15 100
15 2\n1 4\n2 12\n1 9\n3 1\n1 15\n9 3\n12 64\n4 10\n2 6\n80 100\n5
10\n6 24\n12 80\n6 150\n120 9\n150 120
将其粘贴到测试小提琴的提示中。