Created
December 28, 2018 03:57
-
-
Save ehborisov/e667d59704186c14d05a111b1b0eef6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solveNQueens(n): | |
""" | |
Returns all possible combinations of N queens placement. | |
:type n: int | |
:rtype: List[List[str]] | |
""" | |
board = [['.'] * n for _ in range(n)] | |
solutions = [] | |
def solve_for(n_q, row, b): | |
if n_q == 0: | |
solutions.append([''.join(row) for row in b]) | |
else: | |
for i in range(row, n): | |
if 'Q' in b[i]: | |
continue | |
solution_at_row = False | |
for j in range(0, n): | |
if is_attacked(i, j, n, b): | |
continue | |
b[i][j] = 'Q' | |
solve_for(n_q - 1, i, b) | |
b[i][j] = '.' | |
if not solution_at_row: | |
break | |
solve_for(n, 0, board) | |
return solutions | |
def is_attacked(i, j, n, board): | |
print(i, j, n, board) | |
for k in range(0, n): | |
if board[k][j] == 'Q': | |
return True | |
for m in range(0, n): | |
if board[i][m] == 'Q': | |
return True | |
# parallel to main diagonal | |
d, e = (i - j, 0) if i >= j else (0, j - i) | |
while d < n and e < n: | |
if board[d][e] == 'Q': | |
return True | |
d += 1 | |
e += 1 | |
# parallel to the secondary diagonal | |
d = i | |
e = j | |
while d < n and e >= 0: | |
if board[d][e] == 'Q': | |
return True | |
d += 1 | |
e -= 1 | |
d = i | |
e = j | |
while d >= 0 and e < n: | |
if board[d][e] == 'Q': | |
return True | |
d -= 1 | |
e += 1 | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment