Place n queens on an n×n chessboard such that no two queens attack each other. Return all distinct solutions. 'Q' = queen, '.' = empty.
n = 4[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]n = 1[["Q"]]Row-by-row placement ensures one queen per row. cols set checks columns, diag1(row-col) checks ↘ diagonals, diag2(row+col) checks ↗ diagonals. Three O(1) set lookups per cell give massive pruning. Only valid columns are explored at each row.
Trying every way to place n queens on n squared cells is enormous. There is exactly one queen per row, so place them row by row.
For the current row, try each column. Skip a column if a queen above shares its column or one of its diagonals. Place the queen, recurse to the next row, then remove it.
One queen per row, and check column and both diagonals. Row minus column and row plus column identify the diagonals.
Run the animation above on your own input, or watch the 1:32 video explanation of N-Queens with a dry run and Java code.