The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
Example
There exist two distinct solutions to the 4-queens puzzle:
class Solution:
"""
Get all distinct N-Queen solutions
@param n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
# write your code here
result = []
usedColumns = [0] * n
if n <= 0:
return result
self.search(usedColumns, result, 0)
return result
def search(self, usedColumns, result, row):
n = len(usedColumns)
if n == row:
result.append(self.printChessBoard(usedColumns))
return
for i in range(n):
if self.isValid(usedColumns, row, i):
usedColumns[row] = i
self.search(usedColumns, result, row + 1)
def isValid(self, usedColumns, row, col):
for i in range(row):
# check the columns is valid
if usedColumns[i] == col:
return False
# left-top to right-bottom, right-top to left - bottom.
if row - i == abs(col - usedColumns[i]) :
return False
return True
def printChessBoard(self, usedColumns):
chessboard = []
n = len(usedColumns)
for r in range(n):
line = ""
for c in range(n):
if usedColumns[r] == c:
line += "Q"
else:
line += "."
chessboard.append(line)
return chessboard