# Solution to the 8 Queens Problem class EightQueens (object): # initialize the board def __init__ (self, n = 8): self.board = [] self.n = n for i in range (self.n): row = [] for j in range (self.n): row.append ('*') self.board.append (row) # check if no queen captures another def isValid (self, row, col): for i in range (self.n): if (self.board[row][i] == 'Q' or self.board[i][col] == 'Q'): return False for i in range (self.n): for j in range (self.n): rowDiff = abs (row - i) colDiff = abs (col - j) if (rowDiff == colDiff) and (self.board[i][j] == 'Q'): return False return True def recursiveSolve (self, col): if (col == self.n): return True else: for i in range (self.n): if (self.isValid (i, col)): self.board[i][col] = 'Q' if (self.recursiveSolve (col + 1)): return True self.board[i][col] = '*' return False # solve the problem def solve (self): for i in range (self.n): if (self.recursiveSolve (i)): self.printBoard () # print the board def printBoard (self): for i in range (self.n): for j in range (self.n): print (self.board[i][j], end = ' ' ) print () def main(): # create object queens = EightQueens (8) queens.solve() main()