PythiloLesson 30 of 32 · progress kept in this browser

Backtrack through N queens

Backtracking builds a solution one choice at a time and undoes a choice as soon as it cannot lead anywhere. For N queens, place one queen per row and reject any column or diagonal already under attack.

cols, diag1, diag2 = set(), set(), set()
row, col = 2, 1
print(row - col, row + col)   # 1 3
Your task

Write solve(n) returning every solution as a list of column indices, one per row, in lexicographic order.