You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.3 KiB

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