[英]My Code isn't compiling, can anyone help me figure out what I'm doing wrong?
[英]C++ recursion segfault. Can you help me see what I'm doing wrong?
這是我第一次使用遞歸來做除了查找數字的階乘之外的事情。 我正在構建一個程序來在一個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);
}
在所有情況下,您都在向所有方向遞歸。 考慮這個減少的遞歸版本:
void findword(... int x, int y, ...) {
...
findword(... x, y+1, ...);
findword(... x, y-1, ...);
...
}
現在考慮何時調用x == 5
和y == 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?
現在,考慮算法。 在尋找單詞時,首先選擇第一個字符,然后選擇一個方向 ,然后測試朝那個方向可以組成一個單詞的字母數。 您實現的算法嘗試不僅在行中而且以任何隨機形狀查找單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.