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.