C ++递归段错误。你能帮我看看我做错了什么吗?

时间:2014-02-06 03:56:37

标签: c++ gcc recursion segmentation-fault boggle

这是我第一次使用递归来做除了查找数字的阶乘之外的事情。我正在构建一个程序来在一个boggle board中找到单词。以下是导致段错误的函数:

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

1 个答案:

答案 0 :(得分:3)

在所有情况下,您都在向所有方向递归。考虑这个减少的递归版本:

void findword(... int x, int y, ...) {
   ...
   findword(... x, y+1, ...);
   findword(... x, y-1, ...);
   ...
}

现在考虑何时调用x == 5y == 5(例如,任何其他位置都同样好)。我在下面使用缩​​进来表示嵌套调用:

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?

现在,考虑算法。在寻找单词时,首先选择第一个字符,然后选择方向,然后在方向上进行测试可以组成单词的字数。您实现的算法尝试不仅在行中而且以任何随机形状查找单词。