Search code examples
c++visual-studio-2008recursionbacktracking

Recursion backtracking with pruned searches


I have a recursive function that parses a trie string database replacing with all the characters in each node. On the recursive call an edit count is incremented and then the new string is tested for 1) if all nodes have been parsed and 2) if the string equals a string on a list of approved strings. So, the result should be the edit distance between the test string and all the possible strings in the database.

void suggestCorrections(nodeT *w, Set<CorrectionT> &suggest, int index, string test, string final, double edits)
{   
    if (word == "") {
        if (containsCode(final)) //compare with list of approved strings
            updateSet(w, suggest, final, edits);

    } else  { //continue to search path
        if( w->alpha.size() > index) {
            if (test[0] == w->alpha[index].char)
                suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+test[0], edits); //follow matching char 
            suggestCorrections(w, suggest, ++index, test, final, edits);//check next path
            suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+w->alpha[index].char, ++edits);//follow path
        }
    }
}

struct CorrectionT {
    double editDistance; //stackItems
    string suggestedWord; //stackItems
    string suggestDescription;
    string gates;
};

The problem is when the w->alpha.size() is equal to index - the path is correctly ended but then the last path suggestCorrections(w->alpha[index].next, suggest, 0, test.substr(1), final+w->alpha[index].char, ++edits); is entered, when index is incremented past the end of w->alpha. Why does the happen? And how is it fixed?

I think it is backtracking back through the function when the end of the path is met. I don't want it to backtrack. I checked the call stack and setup breaks throughout but this seems like a conceptual issue not a bug. I also read a textbook chapter on recursion and the Wikipedia page - I understand the concept of backtracking, but not the implementation (or desired lack of) in this specific case. I used backtracking to build the trie database and it worked there, but that is different enough from here that I cannot figure this out.


Solution

  • In the second-to-last call to suggestCorrections, you're passing ++index. That is incrementing the value of index, which is then passed in on the last call to suggestCorrections. I haven't really tried to understand your code, but it looks like you probably just want to pass index+1 in the second-to-last call, rather than ++index.

    In general, hiding increment operations inside function call arguments isn't good coding practice (in my opinion, at least). It makes it hard to read and debug the code.