gcc - C++ recursion segfault. Can you help me see what I'm doing wrong? -
this first time i've used recursion other find factorial of number. i'm building program find words in boggle board. following function 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: not prevent using same tile twice in 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 recursing in directions in cases. consider reduced recursion version:
void findword(... int x, int y, ...) { ... findword(... x, y+1, ...); findword(... x, y-1, ...); ... }
now consider when called x == 5
, y == 5
(for example, other position good). using indentation below represent nested calls:
findword(... 5, 5, ...) findword(..., 5, 6, ...) // x, y+1 ... findword(..., 5, 5, ...) // x, y-1 // ouch! same before, eventually: findword(..., 5, 6, ...) findword(..., 5, 5, ...) // ouch!... here again! shall continue?
now, think algorithm. when looking word, first select first character, direction , test going in that direction how many letters can make word. algorithm implemented attempts find words not in lines in random shape.
Comments
Post a Comment