Skip to content

Instantly share code, notes, and snippets.

@siddhantkushwaha
Created August 4, 2019 05:04
Show Gist options
  • Save siddhantkushwaha/2950337247fbc69448801c40be70723e to your computer and use it in GitHub Desktop.
Save siddhantkushwaha/2950337247fbc69448801c40be70723e to your computer and use it in GitHub Desktop.
N-Queens: backtrack to print all solutions
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 'Q':
return False
i = row
j = col
while i >= 0 and j >= 0:
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
i = row
j = col
while j >= 0 and i < len(board):
if board[i][j] == 'Q':
return False
i = i + 1
j = j - 1
return True
def solveNQUtil(board, col):
if col == len(board):
solution = [''.join(row) for row in board]
yield solution
for i in range(len(board)):
if (isSafe(board, i, col)):
board[i][col] = 'Q'
yield from solveNQUtil(board, col + 1)
board[i][col] = '.'
def solveNQ():
board = [['.' for j in range(8)]
for i in range(8)]
return solveNQUtil(board, 0)
for solution in solveNQ():
print(solution)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment