Backtracking

Backtracking search is simply depth-first search. At each iteration, we choose a variable to try and we choose an ordering of that variable's domain.


//This takes in an assignment (either partial or complete)
BACKTRACKING(assignment)
    if assignment is complete
        return assignment
    end

    X ← choose an unassigned variable
    D ← choose an ordering of the values in the domain of X

    for each d in D
        Augment assignment with (X=d)   //Assignment has now been updated      
        [OPTIONAL: ADD INFERENCE HERE]

        if assignment is consistent // How consistency is detected changes if inference is added
            result ← BACKTRACKING(assignment)

            //We found a solution!
            if result != FAILURE
                return result
            end

            //This value didn't work...move on to the next
            remove (X=d) from assignment
        end
    end

    //None of the values in the domain worked...we've hit a dead end
    return FAILURE
end