8-queens problem in Python.
Hi! I only start teaching Python, so could someone explain the code written below (found in the Internet)? Some pieces of the code are compli
Here is my solution. It is much more easier to understand and straighforward:
def under_attack(row, column, existing_queens):
if not len(existing_queens): return False
for queen in existing_queens:
if not len(queen):
continue
r,c = queen
if r == row: return True # Check row
if c == column: return True # Check column
if (column-c) == (row-r): return True # Check left diagonal
if (column-c) == -(row-r): return True # Check right diagonal
return False
def iter_solve(n):
solutions = None
for row in range(1, n+1):
# for each row, check all valid column
solutions = check(solutions, row, n)
return solutions
def check(solutions, row, n):
new_solutions = []
for column in range(1, n+1):
if not solutions or not len(solutions):
new_solutions.append([] + [(row, column)])
else:
for solution in solutions:
if not under_attack(row, column, solution):
new_solutions.append(solution + [(row, column)])
return new_solutions