This is the first time I've used recursion to do something other than find the factorial of a number. I'm building a program to find words in a boggle board. Following is the function that is resulting in segfaults:
void findWord(vector<string>& board, set<string>& dictionary,
string prefix, int row, int column){
prefix += getTile(board, row, column);
if(prefix.length() > biggestWordLength)
return;
if(isOutOfBounds(row, column))
return;
if(isWord(prefix, dictionary) == 1)
foundWords.insert(prefix);
if(isWord(prefix, dictionary) == 0)
return;
//Note: this does not prevent using the same tile twice in a word
findWord(board, dictionary, prefix, row-1, column-1);
findWord(board, dictionary, prefix, row-1, column);
findWord(board, dictionary, prefix, row-1, column+1);
findWord(board, dictionary, prefix, row, column-1);
findWord(board, dictionary, prefix, row, column+1);
findWord(board, dictionary, prefix, row+1, column-1);
findWord(board, dictionary, prefix, row+1, column);
findWord(board, dictionary, prefix, row+1, column+1);
}
You are recursing in all directions in all cases. Consider this reduced recursion version:
void findword(... int x, int y, ...) {
...
findword(... x, y+1, ...);
findword(... x, y-1, ...);
...
}
Now consider when it is called for x == 5
and y == 5
(for example, any other position would be just as good). I am using indentation below to represent nested calls:
findword(... 5, 5, ...)
findword(..., 5, 6, ...) // x, y+1
...
findword(..., 5, 5, ...) // x, y-1
// ouch! this is just the same as before, so it will eventually:
findword(..., 5, 6, ...)
findword(..., 5, 5, ...)
// ouch!... here again! shall I continue?
Now, think about the algorithm. When looking for a word, you first select the first character, then a direction and then test going in that direction how many letters can make up a word. The algorithm you implemented attempts to find words not just in lines but in any random shape.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.