1

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);
}
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
bweber13
  • 360
  • 4
  • 13
  • 1
    You should place the bounds check *before* the part where you add a character to the end of `prefix` – Brian Bi Feb 06 '14 at 03:58

1 Answers1

3

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.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • Now I have a new problem. Something with the way I'm passing my arguments is causing a segfault. I'm updating my question, can you help me again? – bweber13 Feb 06 '14 at 17:15
  • You should not *update* questions with new content. You should create a separate new question. You update the question to provide more information on the original issue, clarify.... you don't *change*. Since we are at it, it is impossible to even answer the update without seeing the definition of the question. Please rollback the question, ask another one and provide all required information – David Rodríguez - dribeas Feb 06 '14 at 17:45