alpar@1: /* QUEENS, a classic combinatorial optimization problem */ alpar@1: alpar@1: /* Written in GNU MathProg by Andrew Makhorin */ alpar@1: alpar@1: /* The Queens Problem is to place as many queens as possible on the 8x8 alpar@1: (or more generally, nxn) chess board in a way that they do not fight alpar@1: each other. This problem is probably as old as the chess game itself, alpar@1: and thus its origin is not known, but it is known that Gauss studied alpar@1: this problem. */ alpar@1: alpar@1: param n, integer, > 0, default 8; alpar@1: /* size of the chess board */ alpar@1: alpar@1: var x{1..n, 1..n}, binary; alpar@1: /* x[i,j] = 1 means that a queen is placed in square [i,j] */ alpar@1: alpar@1: s.t. a{i in 1..n}: sum{j in 1..n} x[i,j] <= 1; alpar@1: /* at most one queen can be placed in each row */ alpar@1: alpar@1: s.t. b{j in 1..n}: sum{i in 1..n} x[i,j] <= 1; alpar@1: /* at most one queen can be placed in each column */ alpar@1: alpar@1: s.t. c{k in 2-n..n-2}: sum{i in 1..n, j in 1..n: i-j == k} x[i,j] <= 1; alpar@1: /* at most one queen can be placed in each "\"-diagonal */ alpar@1: alpar@1: s.t. d{k in 3..n+n-1}: sum{i in 1..n, j in 1..n: i+j == k} x[i,j] <= 1; alpar@1: /* at most one queen can be placed in each "/"-diagonal */ alpar@1: alpar@1: maximize obj: sum{i in 1..n, j in 1..n} x[i,j]; alpar@1: /* objective is to place as many queens as possible */ alpar@1: alpar@1: /* solve the problem */ alpar@1: solve; alpar@1: alpar@1: /* and print its optimal solution */ alpar@1: for {i in 1..n} alpar@1: { for {j in 1..n} printf " %s", if x[i,j] then "Q" else "."; alpar@1: printf("\n"); alpar@1: } alpar@1: alpar@1: end;