用JAVA解决一个难题。下面的描述中提到了挑战。我面临的逻辑错误也在下面的描述中
卢卡什非常喜欢定向运动,这项运动需要在崎岖的地形中找到控制点。为了娱乐NWERC参与者,卢卡什想组织一场定向比赛。然而,在瑞典11月这样寒冷的天气里,参赛者不可能在户外进行比赛,因此他决定跳上室内比赛的新潮流,把比赛安排在林克平大学的B大楼内
卢卡什已经决定了控制点的位置。他还决定了比赛的确切长度,所以剩下的唯一一件事就是决定访问控制点的顺序,以便整个比赛的长度符合他的意愿。因为这并不总是可能的,他要求你写一个程序来帮助他
输入格式
输入包括:
一行两个整数n(2≤ N≤ 14) 和L(1≤ L≤ 1015),控制点的数量和比赛的预期长度; n行,每个行有n个整数。第i行的第j个整数dij表示控制点i和j(1)之间的距离≤ dij≤ 对于i=6,dii)。所有人1≤ i、 j,k≤ N在这种情况下,dij=dji和dij≤ dik+dkj。 输出格式
如果可以按某种顺序访问所有控制点一次,并直接返回到第一个控制点,使总距离正好为L,则输出一行“可能”,否则为“不可能”
样本输入
3 5
0 1 3
1 0 3
4 1 0
样本输出
possible
代码的问题是,函数checkscenario()的else循环中的for循环只考虑第一次迭代,结果返回false。它不会检查下一次迭代,下一次迭代将返回true,从而给出正确的解决方案强>
让我们使用示例输入进行解释。最初,函数按如下方式获取参数值:-
controlptsleft={0,1,2,3}
//These are the control pts which haven't been visited.
指数=0
//This is the control pt that I am at.
控制矩阵=
0 1 3
1 0 3
4 1 0
L=5
//The desired length.
总和=0
//Till now we haven't trailed the control pts. So, sum = 0.
public static boolean checkscenario(ArrayList<Integer> controlptsleft, int index, int[][] controlmatrix, int L, int sum){
int row = controlptsleft.get(index);
//row stores the value in the ArrayList controlptsleft at the index.
controlptsleft.remove(index);
//The controlpt is removed. The first time 0 will be removed from arrayList controlptsleft.
if(controlptsleft.isEmpty()){
//When the ArrayList controlptsleft is empty, we have to go back to the first controlflag.
int temp = controlmatrix[row][0];
//temp stores the distance between the control flag where we are at and the starting control flag.
if(L == (sum + temp))
return true;
}
else{
for(int i=0;i<controlptsleft.size();i++){
int temp = controlmatrix[row][controlptsleft.get(i)];
//temp stores the distance between the control flag where we are at and the whatever controlflag we get during the iteration.
ArrayList<Integer> tempList = controlptsleft;
boolean finalres = checkscenario(tempList,i,controlmatrix,L,(sum + temp));
//Here, i is sent so that when it enters the function again the index i (along with the value) in ArrayList tempList will be deleted.
if(finalres)
return true;
}
}
return false;
}
# 1 楼答案
万一有人想知道,我想出了这个挑战的答案
首先,我要感谢汉诺·宾德的评论。我意识到我错在哪里了
在函数的else循环中检查场景
我所做的是,我直接将controlptsleft的引用复制到圣殿骑士。我意识到了这个错误,于是我初始化了圣殿骑士,并使用了。addAll将所有值从控制ptsleft放入圣殿骑士。 下面的代码说明了我上面的意思
如果有人有更好的JAVA解决方案来应对上述挑战。请随意发布他们的代码,这样我就可以学习如何更好地编写代码