簡體   English   中英

運行Boggle Solver需要一個多小時才能運行。 我的代碼出了什么問題?

[英]Running Boggle Solver takes over an hour to run. What is wrong with my code?

所以我在NetBeans IDE上運行java中的Boggle Solver。 當我運行它時,我必須在10分鍾左右后退出,因為它最終需要大約2小時才能完全運行。 我的代碼有什么問題,或者一種方法會更快嗎?

public void findWords(String word, int iLoc, int jLoc, ArrayList<JLabel> labelsUsed){

    if(iLoc < 0 || iLoc >= 4 || jLoc < 0 || jLoc >= 4){
        return;
    }

    if(labelsUsed.contains(jLabels[iLoc][jLoc])){
        return;
    }

    word += jLabels[iLoc][jLoc].getText();
    labelsUsed.add(jLabels[iLoc][jLoc]);

    if(word.length() >= 3 && wordsPossible.contains(word)){
        wordsMade.add(word);
    }

    findWords(word, iLoc-1, jLoc, labelsUsed);
    findWords(word, iLoc+1, jLoc, labelsUsed);
    findWords(word, iLoc, jLoc-1, labelsUsed);
    findWords(word, iLoc, jLoc+1, labelsUsed);
    findWords(word, iLoc-1, jLoc+1, labelsUsed);
    findWords(word, iLoc-1, jLoc-1, labelsUsed);
    findWords(word, iLoc+1, jLoc-1, labelsUsed);
    findWords(word, iLoc+1, jLoc+1, labelsUsed);

    labelsUsed.remove(jLabels[iLoc][jLoc]);
}

這是我從這里調用此方法的地方:

public void findWords(){
    ArrayList <JLabel> labelsUsed = new ArrayList<JLabel>();
    for(int i=0; i<jLabels.length; i++){
        for(int j=0; j<jLabels[i].length; j++){
            findWords(jLabels[i][j].getText(), i, j, labelsUsed);
            //System.out.println("Done");
        }
    }
}

編輯:BTW我正在使用GUI,並使用JLabel顯示板上的字母。

好吧,對於初學者來說,你運行ArrayList.contains()labelsUsed.contains(..) )很多次,每次都是O(n) - 你應該考慮使用更有效的數據結構 - 如果可能的話,如Set (不)欺騙元素)。

你混合迭代和遞歸的方法,所以findWords方法被稱為 n^n次,而不是n倍。

刪除findWords方法的八個findWords...行,或刪除main的兩個for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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