39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from typing import List, Tuple, Optional
|
|
|
|
def solve_backtracking(n: int, find_all: bool = False) -> List[List[int]]:
|
|
"""
|
|
Backtracking algorithm for N-Queens.
|
|
Returns a list of solutions. Each solution is a list of column indices for each row.
|
|
"""
|
|
solutions = []
|
|
board = [-1] * n # board[row] = col
|
|
cols = [False] * n
|
|
diag1 = [False] * (2 * n - 1) # row + col
|
|
diag2 = [False] * (2 * n - 1) # row - col + (n - 1)
|
|
|
|
def backtrack(row: int):
|
|
if row == n:
|
|
solutions.append(board[:])
|
|
return True
|
|
|
|
for col in range(n):
|
|
if not cols[col] and not diag1[row + col] and not diag2[row - col + n - 1]:
|
|
board[row] = col
|
|
cols[col] = True
|
|
diag1[row + col] = True
|
|
diag2[row - col + n - 1] = True
|
|
|
|
if backtrack(row + 1):
|
|
if not find_all:
|
|
return True
|
|
|
|
# Backtrack
|
|
cols[col] = False
|
|
diag1[row + col] = False
|
|
diag2[row - col + n - 1] = False
|
|
|
|
return False
|
|
|
|
backtrack(0)
|
|
return solutions
|