【问题标题】:Running Boggle Solver takes over an hour to run. What is wrong with my code?运行 Boggle Solver 需要一个多小时才能运行。我的代码有什么问题?
【发布时间】:2012-12-03 16:54:59
【问题描述】:

所以我在 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");
        }
    }
}

编辑:顺便说一句,我使用的是 GUI,板上的字母是使用 JLabel 显示的。

【问题讨论】:

  • jlabels的大小是多少?
  • 您是否尝试分析您的代码?
  • 它大部分时间都在做什么,例如你的 CPU 分析器说什么?

标签: java performance solver boggle


【解决方案1】:

好吧,对于初学者来说,你运行了很多次ArrayList.contains() (labelsUsed.contains(..)),每次都是O(n) - 你应该考虑使用更高效的数据结构 - 如果可能的话,比如 Set(没有欺骗元素)。

【讨论】:

  • 使用 HashSet 可能会有很大帮助。 O(1) 比 O(n) 好很多
【解决方案2】:

您正在混合使用迭代和递归方法,因此 findWords 方法被称为 类似 n^n 次而不是 n 次。

要么删除findWords 方法的八个findWords... 行,要么删除main 的两个for 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多