-
-
Save rrampage/8f7fb7e0a53b1a5ec0161386ded429cc to your computer and use it in GitHub Desktop.
N Queens Backtracking solution
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
"""N-queens problem""" | |
def is_atk(x1, x2): | |
"Check if 2 queens attack each other" | |
r1, c1, r2, c2 = *x1, *x2 | |
return r1 == r2 or c1 == c2 or r1-c1 == r2-c2 or r1+c1 == r2+c2 | |
def backtrack(n, r, Q): | |
"Iterate through each column in a row and backtrack if the cell is not valid" | |
if n == r: return True | |
for c in range(n): | |
s = True | |
for q in range(r): | |
if is_atk((r, c), Q[q]): | |
s = False | |
break | |
if s: | |
Q[r] = (r,c) | |
if backtrack(n, r+1, Q): return True | |
return False | |
def n_queens_solution(n): | |
"Generate a solution to N-Queens" | |
Q = [None]*n | |
return Q if backtrack(n, 0, Q) else None | |
print(n_queens_solution(4)) | |
print(n_queens_solution(8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment