This is a backtracking implementation of the 8 queens puzzle. What the possible ways to return the first perm
outside of the function.
def can_be_extended_to_solution(perm: List[int]) -> bool:
"""Check if two queens attack each other diagonally.
Args:
perm: The permutation of the queens.
Returns:
True if the permutation can be extended to a solution, False otherwise.
"""
i = len(perm) - 1
for j in range(i):
# Here, we are not using the abs() function because we know that i > j.
if i - j == abs(perm[i] - perm[j]):
return False
return True
def extend(perm: List[int], n:int):
if len(perm) == n:
print(perm)
sys.exit()
for k in range(n):
if k not in perm:
perm.append(k)
if can_be_extended_to_solution(perm):
extend(perm, n)
perm.pop()
I have tried using a global variable but that does not seem to work. Perhaps because a call is made to sys.exit()
.