-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathprob054_n_queens.py
59 lines (42 loc) · 1.78 KB
/
prob054_n_queens.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
N-queens problem in CPMpy
CSPlib prob054
Problem description from the numberjack example:
The N-Queens problem is the problem of placing N queens on an N x N chess
board such that no two queens are attacking each other. A queen is attacking
another if it they are on the same row, same column, or same diagonal.
Here are some different approaches with different version of both
the constraints and how to solve and print all solutions.
This CPMpy model was written by Hakan Kjellerstrand ([email protected])
See also my CPMpy page: http://hakank.org/cpmpy/
Modified by Ignace Bleukx
"""
import sys
import numpy as np
from cpmpy import *
def n_queens(n=16):
queens = intvar(1, n, shape=n)
# Constraints on columns and left/right diagonal
model = Model([
AllDifferent(queens),
AllDifferent(queens - np.arange(n)),
AllDifferent(queens + np.arange(n)),
])
return model, (queens,)
def print_sol(queens):
queens = queens.value()
board = np.zeros(shape=(len(queens), len(queens)), dtype=str)
for i,q in enumerate(queens):
board[i,q-1] = chr(0x265B)
print(np.array2string(board,formatter={'str_kind':lambda x : x if len(x) != 0 else " "}))
print()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-n", type=int, default=16, help="Number of queens")
parser.add_argument("--solution_limit", type=int, default=10, help="Number of solutions, find all by default")
args = parser.parse_args()
model, (queens,) = n_queens(args.n)
n_sols = model.solveAll(solution_limit=args.solution_limit,
display = lambda : print_sol(queens))
print("num_solutions:", n_sols)