Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- SIZE = 8
- numSolutions = 0
- board = {'numQueens': 0} # keys are (x, y), values are 'Q', '.', 'x'
- QUEEN = 'Q'
- EMPTY = '.'
- def placeQueen(board):
- board = copy.copy(board)
- for y in range(SIZE):
- for x in range(SIZE):
- canPlaceQueenHere = True
- # Check all the under-attack positions for existing queens:
- for column in range(SIZE): # Check the row of (x, y)
- if board.get((column, y), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- for row in range(SIZE): # Check the column of (x, y)
- if board.get((x, row), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- for diagonalOffset in range(1, SIZE): # Check the diagonals of (x, y)
- if board.get((x + diagonalOffset, y + diagonalOffset), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- if board.get((x - diagonalOffset, y - diagonalOffset), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- if board.get((x + diagonalOffset, y - diagonalOffset), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- if board.get((x - diagonalOffset, y + diagonalOffset), EMPTY) == QUEEN:
- canPlaceQueenHere = False
- if canPlaceQueenHere:
- # Placing the queen on the board:
- board[(x, y)] = QUEEN
- board['numQueens'] += 1
- if board['numQueens'] == SIZE:
- printBoard(board)
- else:
- placeQueen(board) # RECURSIVE CASE
- # Undo this most recent queen placement:
- board[(x, y)] = EMPTY
- board['numQueens'] -= 1
- return # BASE CASE
- def printBoard(board):
- for y in range(SIZE):
- for x in range(SIZE):
- space = board.get((x, y), EMPTY)
- print(space + ' ', end='')
- print()
- print()
- placeQueen(board)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement