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