【问题标题】:C++ recursion segfault. Can you help me see what I'm doing wrong?C++ 递归段错误。你能帮我看看我做错了什么吗?
【发布时间】:2014-02-06 03:56:37
【问题描述】:

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

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

【问题讨论】:

  • 您应该在prefix末尾添加字符的部分之前放置边界检查

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


【解决方案1】:

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

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?

现在,考虑一下算法。查找单词时,您首先选择第一个字符,然后选择方向,然后测试该方向有多少个字母可以组成一个单词。您实现的算法不仅尝试查找单词,还尝试查找任何随机形状的单词。

【讨论】:

  • 很棒的解释!感谢您的帮助!
  • 现在我有一个新问题。我传递论点的方式导致了段错误。我正在更新我的问题,你能再帮我一次吗?
  • 您不应使用新内容更新问题。您应该创建一个单独的新问题。您更新问题以提供有关原始问题的更多信息,澄清....您不会更改。既然我们在这,即使没有看到问题的定义,也无法回答更新。请回滚问题,再问一个问题并提供所有必需的信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多