[英]I'm having a lot of trouble using recursion with graphs. Java
public int rec(String letterOne, String letterTwo, int steps)
{
String currentLetter = "";
if(letterOne.equals(letterTwo))
{
return steps;
}
for(int x=0; x<graph.length; x++)
{
for (int y=0; y<graph[x].size(); y++)
{
currentLetter = graph[x].get(y).toString();
if (currentLetter.equals(letterOne)&&!checkForLet(checked,currentLetter))
{
checked.add(currentLetter);
if (y==0)
{
return rec(graph[x].get(1).toString(),letterTwo,steps+1);
}
else
{
return rec(graph[x].get(0).toString(),letterTwo,steps+1);
}
}
}
}
return -1;
}
这是图表
CA XY RS YS ST TB AB BD RJ CE
我已经将所有连接都连接到了 ArrayList[]。 这是我的递归方法,它现在应该返回它在输入图中找到的第一条路径。 我想我已经很接近搞清楚了,如果我不擅长这个,我很抱歉; 这是我第一次这样做。 谢谢。
您的代码的问题是,当您遍历图形的边时,您只检查包含 letterOne 的第一条边,然后返回结果,例如,对于从 C 到 B 的路径,rec 将按此顺序调用:
rec("C", "B", 0)
rec("A", "B", 1)
rec("C", "B", 2)//returns -1 and whole function returns -1
这是基于与您所拥有的类似想法的工作代码:
private static List<String>[] graph = new List[]{
List.of("C", "A"),
List.of("X", "Y"),
List.of("R", "S"),
List.of("Y", "S"),
List.of("S", "T"),
List.of("T", "B"),
List.of("A", "B"),
List.of("B", "D"),
List.of("R", "J"),
List.of("C", "E")
};
int pathLength(String from, String to){
return pathLengthRec(from, to, 0);
}
Set<String> checkedLetters=new HashSet<>();
private int pathLengthRec(String from, String to, int steps) {
if(from.equals(to)){
return steps;
}
if (checkedLetters.add(from)) {//returns true if letter was not yet visited
for (List<String> edge : graph) {
if (edge.contains(from)) {
String nextLetterCandidate = edge.get(0).equals(from) ? edge.get(1) : edge.get(0);
int pathLength = pathLengthRec(nextLetterCandidate,to,steps + 1);
if (pathLength != -1) { //here is the important difference - if the function returns -1 for one of the edges try with other edges
return pathLength;
}
}
}
}
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.