prometheus800

ВИ Тест 4: N-Queens Problem (CSP)

Apr 18th, 2021
781
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from constraint import *
  2.  
  3. if __name__ == '__main__':
  4.     problem = Problem(BacktrackingSolver())
  5.  
  6.     num_queens = int(input())
  7.  
  8.     queens = range(1, num_queens + 1)
  9.     domain = [(i, j) for i in range(num_queens) for j in range(num_queens)]
  10.  
  11.     problem.addVariables(queens, domain)
  12.    
  13.     # ----------------Constraints begin here----------------
  14.     for queen1 in queens:
  15.         for queen2 in queens:
  16.             if queen1 < queen2:
  17.                 # Diagonal constraints
  18.                 problem.addConstraint(lambda q1, q2: (abs(q1[0] - q2[0]) != abs(q1[1] - q2[1])), (queen1, queen2))
  19.                 # Row and column constraint
  20.                 problem.addConstraint(lambda q1, q2: q1[0] != q2[0] and q1[1] != q2[1], (queen1, queen2))
  21.     # ------------------------------------------------------
  22.     # If there are less than 7 queens, print only the number of solutions
  23.     if num_queens < 7:
  24.         print(len(problem.getSolutions()))
  25.     else:
  26.         print(problem.getSolution())
  27.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×