#51
N-Queens
hard· Backtrackingruns: 0The n-queens puzzle places n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a board configuration where 'Q' marks a queen and '.' marks an empty square.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 847
class Solution:
def solveNQueens(self, n: int) -> list[list[str]]:
result = []
cols = set()
pos_diag = set()
neg_diag = set()
board = [["."] * n for _ in range(n)]
def backtrack(r: int) -> None:
if r == n:
result.append(["".join(row) for row in board])
return
for c in range(n):
if c in cols or (r + c) in pos_diag or (r - c) in neg_diag:
continue
cols.add(c)
pos_diag.add(r + c)
neg_diag.add(r - c)
board[r][c] = "Q"
backtrack(r + 1)
cols.remove(c)
pos_diag.remove(r + c)
neg_diag.remove(r - c)
board[r][c] = "."
backtrack(0)
return result
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.