Java 运行Boggle Solver需要一个多小时。我的代码有什么问题?
因此,我在NetBeans IDE上运行java中的Boggle解算器。当我运行它时,我必须在大约10分钟后退出,因为它最终需要大约2小时才能完全运行。我的代码是否有问题,或者是否有一种方法可以大大加快速度Java 运行Boggle Solver需要一个多小时。我的代码有什么问题?,java,performance,solver,boggle,Java,Performance,Solver,Boggle,因此,我在NetBeans IDE上运行java中的Boggle解算器。当我运行它时,我必须在大约10分钟后退出,因为它最终需要大约2小时才能完全运行。我的代码是否有问题,或者是否有一种方法可以大大加快速度 public void findWords(String word, int iLoc, int jLoc, ArrayList<JLabel> labelsUsed){ if(iLoc < 0 || iLoc >= 4 || jLoc < 0 ||
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(使用字符串字、int-iLoc、int-jLoc、ArrayList标签){
如果(iLoc<0 | | iLoc>=4 | | jLoc<0 | | jLoc>=4){
返回;
}
if(labelused.contains(jLabels[iLoc][jLoc])){
返回;
}
word+=jLabels[iLoc][jLoc].getText();
添加(jLabels[iLoc][jLoc]);
如果(word.length()>=3&&wordsPossible.contains(word)){
添加(word);
}
findWords(单词、iLoc-1、jLoc、标签使用);
findWords(单词、iLoc+1、jLoc、标签使用);
FindWord(word、iLoc、jLoc-1、使用的标签);
findWords(word、iLoc、jLoc+1、使用的标签);
findWords(单词,iLoc-1,jLoc+1,使用标签);
FindWord(word、iLoc-1、jLoc-1、使用的标签);
FindWord(word、iLoc+1、jLoc-1、使用的标签);
findWords(单词、iLoc+1、jLoc+1、标签使用);
移除(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");
}
}
}
public void findWords(){
ArrayList labelsUsed=新的ArrayList();
对于(int i=0;i),对于初学者,您运行<代码> ARAYLISTER .CONSUTE()/<代码>(<代码> LabelsApple,包含(..)<代码> >很多次,每个都是<代码> O(n)< /代码> -您应该考虑使用更高效的数据结构——比如如果可能的话(没有DUPE元素).您混合了迭代和递归方法,因此findWords
方法被称为n^n
次,而不是n
次
要么删除findWords
方法的八行findWords…
行,要么删除main
循环的两行,jlabels
的大小是多少?是否尝试分析代码?它大部分时间都在做什么?例如,cpu分析程序说什么?使用哈希集可能会你的帮助很大。O(1)比O(n)好得多