The classic N-Queens problem finds a way to place n queens on an n×n chessboard such that no two queens attack each other. This is my solution to the N-Queens problem.
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
grid = [['.' for _ in range(n)] for _ in range(n)]
solved = self.helper(n, 0, grid)
if solved:
return ["".join(item) for item in grid]
else:
return None
def helper(self, n, row, grid):
if n == row:
return True
for col in range(n):
if self.is_safe(row, col, grid):
grid[row][col] = 'Q'
if self.helper(n, row + 1, grid):
return True
else:
grid[row][col] = '.'
return False
def is_safe(self, row, col, board):
for i in range(len(board)):
if board[row][i] == 'Q' or board[i][col] == 'Q':
return False
i = 0
while row - i >= 0 and col - i >= 0:
if board[row - i][col - i] == 'Q':
return False
i += 1
i = 0
while row + i < len(board) and col + i < len(board):
if board[row + i][col - i] == 'Q':
return False
i += 1
i = 1
while row + i < len(board) and col - i >= 0:
if board[row + i][col - i] == 'Q':
return False
i += 1
i = 1
while row - i >= 0 and col + i < len(board):
if board[row - i][col + i] == 'Q':
return False
i += 1
return True
if __name__ == '__main__':
solution = Solution()
print(solution.solveNQueens(8))
An extension to this problems states, find all possible solutions and return them in the form of a list. I tried to extend my solution by adding a column variable to the helper method, which starts at 0 to keep track of one complete solution and the start of the next. Thus the base case becomes
if row == n and col == n:
return True
But that approach doesn't work as every successive recursive call ends up in the wrong column. Can someone help extend this solution to find all possible solutions.