-1

I've found a code that uses Constraints module to create a N-Queen problem solver. My goal with it is to make it show all of the possible solutions, instead of just one it currently shows. I am asking for instructions and explanation, if possible, to achieve that.

Here is the current code:

from constraint import *

problem = Problem()
n = int(input('n: ')) + 1
cols = range(1, n)  # these are the variables
rows = range(1, n)  # these are the domains
problem.addVariables(cols, rows)    # adding multiple variables at once

# that each queen has to be in a separate column is
# implied through the loop and added constraints
for col1 in cols:
    for col2 in cols:
        if col1 < col2:
            problem.addConstraint(lambda row1, row2, col1=col1, col2=col2:
                abs(row1-row2) != abs(col1-col2) and    # this is the diagonal check
                row1 != row2, (col1, col2))             # this is the horizontal check

solution = problem.getSolution()
print(solution)

Here is the output for n = 8:

{1: 8, 2: 4, 3: 1, 4: 3, 7: 7, 5: 6, 6: 2, 8: 5}

I've tried creating an additional 'for' loop, but I can't understand what values should be modified to get alternative results, thus nothing meaningful had happened.

  • I'm not familiar with that module but, if you can define a constraint that excludes a specific solution, you could call getSolution() in a loop that excludes the previous solution at each iteration until no solution is found. (doesn't sound too efficient but if your' just playing with the module I guess it would be fine) – Alain T. Feb 25 '23 at 17:01

1 Answers1

0

I would recommend that you use another module for solving constraint programming problems. For use in Python, OR-Tools is quite popular and has an all-solution n-queens example in the documentation: https://developers.google.com/optimization/cp/queens#the_entire_program

Zayenz
  • 1,914
  • 12
  • 11