gpt4 book ai didi

java - 运行 Boggle Solver 需要一个多小时才能运行。我的代码有什么问题吗?

转载 作者:行者123 更新时间:2023-12-02 07:24:47 24 4
gpt4 key购买 nike

所以我在 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 显示的。

最佳答案

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

关于java - 运行 Boggle Solver 需要一个多小时才能运行。我的代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13688000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com