Menu

[r118]: / queens.py  Maximize  Restore  History

Download this file

32 lines (27 with data), 1.0 kB

 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
import pymprog
# The Queens Problem is to place as many queens as possible on the nxn
# chess board in a way that they do not fight
# each other. This problem is probably as old as the chess game itself,
# and thus its origin is not known, but it is known that Gauss studied
# this problem.
n = 16 #size of chess board
p = pymprog.model('queens')
iboard = pymprog.iprod(range(n), range(n)) #create indices
x = p.var(iboard, 'X', bool) #create variables
#row wise:
p.st([sum(x[i,j] for j in range(n)) <= 1 for i in range(n)])
#column wise:
p.st([sum(x[i,j] for i in range(n)) <= 1 for j in range(n)])
#diagion '/' wise
p.st([sum(x[i,j] for i,j in iboard if i-j == k) <= 1
for k in range(2-n, n-1)])
#diagion '\' wise
p.st([sum(x[i,j] for i,j in iboard if i+j == k) <= 1
for k in range(1, n+n-2)])
p.max(sum(x[t] for t in iboard), 'queens')
p.solve()
for i in range(n):
for j in range(n):
if x[i,j].primal > 0: print 'Q',
else: print '.',
print