0

So I am running a Boggle Solver in java on the NetBeans IDE. When I run it, i have to quit after 10 minutes or so because it will end up taking about 2 hour to run completely. Is there something wrong with my code or a way that will make is substantially faster?

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]);
}

here is where I call this method from:

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");
        }
    }
}

edit: BTW I am using a GUI and the letters on the board are displayed by using a JLabel.

Guy Coder
  • 24,501
  • 8
  • 71
  • 136

2 Answers2

2

Well, for starters, you run ArrayList.contains() (labelsUsed.contains(..))a LOT of times, each is O(n) - you should consider using more efficient data structure - such as a Set if possible (no dupe elements).

amit
  • 175,853
  • 27
  • 231
  • 333
0

You're mixing iterative and recursive approaches, so the findWords method is called something like n^n times instead of n times.

Either remove the eight findWords... lines of the findWords method, or remove the two for loops of your main.

sp00m
  • 47,968
  • 31
  • 142
  • 252