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] )