Last active
March 25, 2023 19:33
-
-
Save swarooprath/85d95b363e740b6c94e7c562c5a2a7ec to your computer and use it in GitHub Desktop.
NQueen with Optimizations that traverses only half of the tree
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
class Solution: | |
def solveNQueens(self, n: int) -> List[List[str]]: | |
def solve_helper(n, slate, i): | |
nonlocal result_list | |
if i >= n: | |
result_list.append(slate[:]) | |
else: | |
for j in filter(lambda x: not is_attack(slate, x), range(n)): | |
slate.append(j) | |
solve_helper(n, slate, i+1) | |
slate.pop() | |
def is_attack(slate, n): | |
return any([p == n or abs(p - n) == (len(slate)-i) for i, p in enumerate(slate)]) | |
def mirror(n, soln): | |
return [(n-i-1) for i in soln] | |
def to_string(soln, n): | |
return ["." * soln[i] + "Q" + "." * (n-soln[i]-1) for i in range(n)] | |
result_list = [] | |
for i in range(n//2): | |
solve_helper(n, [i], 1) | |
mirror_list = [mirror(n, i) for i in result_list] | |
if n % 2 == 1: | |
solve_helper(n, [n//2], 1) | |
return [to_string(r, n) for r in (result_list + mirror_list)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment