Professional Documents
Culture Documents
CSP Nqueen
CSP Nqueen
(N-Queens Problem)
Systematic Search
• MiniZinc model for 4-queens
• Search Tree
• Backtracking (BT)
• Conflict-Directed Backjumping (CBJ)
• Dynamic Backtracking (DB)
• Heuristics
CSP: Search
4-queens in MiniZinc
1 2 3 4
Formulation:
• Variables: one queen per row x1
• Domains: available columns x2
• Constraints: x3
different columns and different diagonals
x4
xi ≠ xj | xi - xj | ≠ | i - j |
4-queens
array[1..4] of var 1..4: BOARD; % variables and domains
Tree:
• each branch defines an assignment
• depth n (number of variables)
• branching factor d (domain size)
CSP: Search
Search tree for 4-queens
1 2 3 4
x1
x2
x3
x4
(1,1,1,1) (2,1,1,1) (3,1,1,1) (4,1,1,1) (4,4,4,4)
CSP: Search
Backtracking Algorithm
Depth-first tree traversal (DFS)
At each node:
• check every completely assigned constraint
• if consistent, continue DFS
• otherwise, prune current branch
• continue DFS
Complexity: O(dn)
CSP: Search
Backtracking on 4-queens
x1 1 2
1 2 3 4
x2 1 2 3 4 1 2 3 4
x1 Q Q
x2 Q Q Q Q
x3 1 2 3 4 1 2 3 4 1 x3 Q Q Q
Q Q
Q
x4 Q Q Q
Q Q
x4 1 2 3 4 1 2 3
25 nodes solution
CSP: Search
Problems of Backtracking
Thrashing: the first choice is
• the same failure can incompatible with
be rediscovered an any last choice
exponential number
of times
Improvements:
• check not completely assigned constraints: propagation
• jumping to the source of failure: non-chronological
backtracking
CSP: Search
Non-chronological Backtracking
X1 Backtrack to the
X2 last culprit variable: X4
X3
X4 X1
X5 1
X6 dead-end X2
3
X7
X8 5 X3
2 X4
Changing X5 does NOT
4
remove the dead-end X5
CSP: Search
X6
Conflict Set
CS(xk): assig. variables in conflict with some value of xk
{x1 ← 1} 1 2 3 4
x1 Q1
{x3 ← 2} {x1}
x2 Q3
x3 Q2 {x1}
{x2 ← 4}
x4 x1 x3 x3 x1 {x1, x3}
x4 CSP: Search
Nogoods
Nogood: subset of incompatible assignments
• original constraints
• during search, new nogoods are discovered
{x1 ← 1} {x1 ← 1}
1 2 3 4
x1=1→x3≠2
{x3 ← 2} x1 Q1 {x2 ← 4}
Q3 new tree
x2
{x2 ← 4} x3 xQ
1=1
2
x4 x1=1x3=2x3=2 x1=1
x4
CSP: Search
Variable Ordering
Static variable ordering: variable associated with level
X1
X2
X3
... ... ... ...
X4
... ... ... ...
Not needed for an exhaustive tree
X1
X2 X3 X4 X4
X3 ... X4 ... X3 ... X2 ...
X4 ... X2 ... X2 ... X3 ...
CSP: Search
Variable Selection
Node q, what is the next variable to assign?
Max-degree:
• First the variable involved in more constraints
• Maximize constraint propagation
Combination:
• First the variable with min domain/degree
CSP: Search