SUNY Geneseo Department of Computer Science


Introduction to Backtracking

Thursday, April 18

CSci 242, Spring 2013
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture

Questions?

Dynamic Programming Question from Exam

Casino with n games played in increasing order, game i wins $wi, moving from game i to j costs $mij

W(i) = max expected winnings for playing game i and later

Answer is W(0), with w0 defined as the money you enter with

Algorithm

    let W[0..n] be a new array
    W[n] = wn - mn∞
    for i = n-1 down to 0
        q = -mi∞
        for j = i+1 to n
            if W[j] - mij > q then q = W[j] - mij
        W[i] = q
    return W[0]

Breaking Substitution Ciphers

Systematically replace each letter of the alphabet with some other to convert plaintext to ciphertext

For example

Breaking a substitution cipher is essentially search for the right reverse substitution

How might you do this algorithmically?

        for w = 1 to number of words
            l = length of word w
            for each word X of length l in dictionary
                try substituting X for word i until a substitution “succeeds” (i.e., no contradiction, user accepts phrase)
            if nothing succeeded, go back to word w-1 (backtrack)

Recursion makes backtracking easier to realize

    boolean solve( w, ciphertext, dictionary, substitutions )
            // true = solved, false = not solved
        if w > length of ciphertext
            offer substitutions to user
            if user accepts
                return true
            else
                return false
        else
            l = length of word w
            for each X of length l in dictionary
                update substitutions, checking for contradictions
                if update possible
                    if solve( w+1, .... )
                        return true
            return false

Next

Algorithmic knowledge for breaking substitution ciphers

For Tuesday: Hash tables


Next Lecture