My Boggle program won't find all the valid words - Java

1.4k views Asked by At

So I am working on a Boggle program in java and I am having trouble getting it to find every possible word.

It finds almost all of them but for the life of me I cannot figure out why it won't get them all.

private void findWords( TreeSet<String> foundWords, String word, Tile t ){
    int i=t.getRow();
    int j=t.getCol();

    //Make sure the tile isn't visited
    if(visited[i][j]) return;

    //Set the current tile to visited
    visited[i][j]=true;

    //Decide what the current word is
    if(t.getLetter().equalsIgnoreCase("q")) word=word+"qu";
    else word=word+t.getLetter();

    //If the string is a word
    if(Boggle.dictionary.search(word)==1){
        //If the word length is greater than or equal to the prefix length
        if(word.length()>=Dictionary.prefixLength){
            //If the word has not already been found
            if(!foundWords.contains(word)){
                //Add the word to the found list
                foundWords.add(word);   
            }
        }
    }

    //Recurse through all neighbor tiles
    for(int curRow=0; curRow<=nRows; curRow++){
        for(int curCol=0; curCol<=nCols; curCol++){
            //Make sure it is not out of bounds
            if((i+curRow<nRows)&&(j+curCol<nCols)){
                findWords(foundWords, word, board[i + curRow][j + curCol]); 
                findWords(foundWords, word, board[i - curRow][j - curCol]); 

                findWords(foundWords, word, board[i + curRow][curCol]); 
                findWords(foundWords, word, board[i - curRow][curCol]); 

                findWords(foundWords, word, board[curRow][j + curCol]); 
                findWords(foundWords, word, board[curRow][j - curCol]); 

                findWords(foundWords, word, board[i + curRow][j - curCol]);
                findWords(foundWords, word, board[i - curRow][j + curCol]);
            }
        }
    }

    //Reset the tile to be not visited
    visited[i][j] = false;
}

This is the method in question; it recursively finds words on the Boggle board.

Anyone have any ideas why it only finds about 75% of the words?

I can attach more code if need be.

1

There are 1 answers

1
pauljwilliams On

I would suggest writing some test cases - I always find that doing this either finds the problem right away, or at least allows you to step through your code with a debugger, and find where reality diverges from your expectations.

Edit: also, your two for loops look odd. Shouldnt you be looking at offsets of -1,0 and 1 in each direction (and discounting 0,0), rather than 0 -> nRows? It seems you're only looking in one direction.