Backtracking

Document last modified: 
  1. DFSbtQ( X[1..i], row )
  2.   if row = 4 then print(X)
  3.   else
  4.       for column ∈ {1, 2, 3, 4 } do
  5.           if not conflicted(X, row+1, column)
  6.              X[row+1] ← column
  7.              DFSbtQ( X, row+1 )
  8.    return

When conflicted next column is examined.

When last column tried, backtrack.

When all rows solved, print solution.

conflicted( X, row, column )

--  pre: X[1..i] first i components of a solution
--  post: True if X[i+1] conflicts at (row, column) with X[1..i]
             False otherwise

 

Question

 

Generic Backtracking Algorithm

DFSbt( X[1..i] )
--  pre: X[1..i] specifies first i components of a solution
--  post: Solution X[1..i]
--           Si+1 is solution i+1
  1. if X[1..i] is a solution then print X[1..i]

  2. else

  3.    for each x ∈ Si+1 do

  4.       if x is consistent with X[1..i] and valid option for problem constraints then

  5.            X[i+1] ← x

  6.            DFSbt( X[1..i+1] )

   Using the generic algorithm  for backtracking:

change( 11, [], 0) prints 4 coins using [5, 2, 2, 2]

change( amount,  X[1..i] )

    -- pre: amount ≥ 0 remaining to change, X the coins used and i ≥ 0 the number of coins so far
    -- post: prints coins used to make change

  1.     if amount = 0 then print X[1..i]
  2.     else
  3.        for coin ∈ { 5, 2 } do
  4.           if remainder ← X[i] - coin ≥ 0 then
  5.              X[i + 1] = coin
  6.              change( remainder, X[i+1] )