Place n queens so none can attack another. Go row by row, track the columns and both diagonals in use, and back up at dead ends.
▼The problem
LeetCode 51 (Hard). Place n queens on an n × n chessboard so that no two attack each other (same row, column or diagonal), and return every distinct solution, each as a list of strings ('Q' and '.').
Examples (from the problem statement): n = 4 → two boards, [".Q..","...Q","Q...","..Q."] and ["..Q.","Q...","...Q",".Q.."]; n = 1 → [["Q"]].
def solveNQueens(n):
out, board = [], []
cols, diag, anti = set(), set(), set()
def place(r):
if r == n: # past the last row
out.append(['.'*c + 'Q' + '.'*(n-c-1) for c in board])
return
for c in range(n):
if c in cols or r - c in diag or r + c in anti:
continue # attacked: skip
cols.add(c); diag.add(r - c); anti.add(r + c)
board.append(c)
place(r + 1)
cols.remove(c); diag.remove(r - c); anti.remove(r + c)
board.pop() # backtrack
place(0)
return outTRY IT ON LEETCODE ▶The solution
def solveNQueens(n):
out, board = [], []
cols, diag, anti = set(), set(), set()
def place(r):
if r == n: # past the last row
out.append(['.'*c + 'Q' + '.'*(n-c-1) for c in board])
return
for c in range(n):
if c in cols or r - c in diag or r + c in anti:
continue # attacked: skip
cols.add(c); diag.add(r - c); anti.add(r + c)
board.append(c)
place(r + 1)
cols.remove(c); diag.remove(r - c); anti.remove(r + c)
board.pop() # backtrack
place(0)
return outTranscript
N-Queens. Place n queens on an n by n chessboard so that no two attack each other, and return every board that works.
A queen attacks along her row, her column and both diagonals. Four queens on a four by four board have exactly two solutions. Eight queens have ninety-two.
The naive way tries every placement. Four queens on sixteen squares make eighteen hundred and twenty boards, and only two survive. For eight queens, it's over four billion. Worse, most of those boards put two queens in the same row, so they were doomed from the start.
The key: each row holds exactly one queen. So place them row by row. To check a square fast, keep three sets: used columns, diagonals named by row minus column, and anti-diagonals named by row plus column. Every square on a diagonal shares that number, so a check is just three lookups.
Let's run four. The first queen takes the corner. In row two, columns one and two are attacked, so she takes column three. Row three is all blocked: dead end. Back up and slide her to column four. Row three takes column two, but row four is blocked. Back up all the way and move the first queen to column two. Now everything fits: column four, column one, column three. First solution.
In code, place takes a row. Past the last row, save the board. Otherwise try each column, skipping any a set already holds. Add the queen to all three sets, recurse on the next row, then remove it. That removal is the backtrack.
Each row has fewer safe columns than the last, so the time grows roughly like n factorial, far less than every board: eight queens take under sixteen thousand checks, not four billion boards. The sets hold at most n entries, so the space is order n.
One queen per row, three sets, undo on the way back. That's N-Queens.