簡體   English   中英

我在使用帶有圖的遞歸時遇到了很多麻煩。 Java

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM