Advertisement
asweigart

8queens

Apr 4th, 2019
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import copy
  2.  
  3. SIZE = 8
  4. numSolutions = 0
  5.  
  6. board = {'numQueens': 0} # keys are (x, y), values are 'Q', '.', 'x'
  7.  
  8. QUEEN = 'Q'
  9. EMPTY = '.'
  10.  
  11. def placeQueen(board):
  12. board = copy.copy(board)
  13. for y in range(SIZE):
  14. for x in range(SIZE):
  15. canPlaceQueenHere = True
  16. # Check all the under-attack positions for existing queens:
  17. for column in range(SIZE): # Check the row of (x, y)
  18. if board.get((column, y), EMPTY) == QUEEN:
  19. canPlaceQueenHere = False
  20.  
  21. for row in range(SIZE): # Check the column of (x, y)
  22. if board.get((x, row), EMPTY) == QUEEN:
  23. canPlaceQueenHere = False
  24.  
  25. for diagonalOffset in range(1, SIZE): # Check the diagonals of (x, y)
  26. if board.get((x + diagonalOffset, y + diagonalOffset), EMPTY) == QUEEN:
  27. canPlaceQueenHere = False
  28. if board.get((x - diagonalOffset, y - diagonalOffset), EMPTY) == QUEEN:
  29. canPlaceQueenHere = False
  30. if board.get((x + diagonalOffset, y - diagonalOffset), EMPTY) == QUEEN:
  31. canPlaceQueenHere = False
  32. if board.get((x - diagonalOffset, y + diagonalOffset), EMPTY) == QUEEN:
  33. canPlaceQueenHere = False
  34.  
  35. if canPlaceQueenHere:
  36. # Placing the queen on the board:
  37. board[(x, y)] = QUEEN
  38. board['numQueens'] += 1
  39.  
  40. if board['numQueens'] == SIZE:
  41. printBoard(board)
  42. else:
  43. placeQueen(board) # RECURSIVE CASE
  44.  
  45. # Undo this most recent queen placement:
  46. board[(x, y)] = EMPTY
  47. board['numQueens'] -= 1
  48. return # BASE CASE
  49.  
  50.  
  51. def printBoard(board):
  52. for y in range(SIZE):
  53. for x in range(SIZE):
  54. space = board.get((x, y), EMPTY)
  55. print(space + ' ', end='')
  56. print()
  57. print()
  58.  
  59. placeQueen(board)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement