Guest User

Untitled

a guest
Jun 22nd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1.  
  2. # Place n non-attacking queens on a nxn chessboard with no queen on either of the major diagonals
  3.  
  4. import sys, random
  5.  
  6. n = int(sys.argv[1])
  7.  
  8. # Every square that a queen may be placed
  9. squares = set([(i,j) for i in range(n) for j in range(n) if i != j and i + j != n-1])
  10. # Every square attacked from this square
  11. canattack = lambda (i0,j0), (i1,j1): i0 == i1 or j0 == j1 or abs(i0 - i1) == abs(j0 - j1)
  12. attacks = dict((s, set([s2 for s2 in squares if canattack(s, s2)])) for s in squares)
  13.  
  14. # nleft = number of queens still to place
  15. # free = squares where a queen can still be placed
  16. def solve(nleft = n, free = squares):
  17.     if nleft > len(free): return None
  18.     if nleft == 1: return tuple(free)
  19.     # Squares that will still remain if the given square is taken
  20.     newfree = dict((square, free - attacks[square]) for square in free)
  21.     # Start with the placements that will leave the most remaining squares
  22.     # If there's a tie, shuffle them randomly (to make this nondeterministic)
  23.     tocheck = sorted(free, key = lambda s: (len(newfree[s]), random.random()), reverse = True)
  24.     for square in tocheck:
  25.         solution = solve(nleft - 1, newfree[square])
  26.         if solution:
  27.             return solution + (square,)
  28.     return None
  29.  
  30. board = solve()
  31. for i in range(n):
  32.     for j in range(n):
  33.         print ("Q" if (i,j) in board else "."),
  34.     print
Add Comment
Please, Sign In to add comment