n-queens.sh — zsh
backtrackingmatrix

Given an integer n, return all distinct solutions to placing n non-attacking queens on an n x n chessboard. Each solution should be represented as an array of n strings, where each string has length n, 'Q' marks a queen, and '.' marks an empty square.

For this question, keep the output deterministic: list boards in the natural depth-first search order created by placing queens row by row, and at each row trying columns from left to right (column 0, then 1, then 2, and so on). When a placement leads to a full valid board, record it immediately; that DFS/backtracking discovery order is the required output order.

Input / output

  • Input: n: int
  • Output: string[][] in DFS order

More examples

  1. n = 1 returns [["Q"]].
  2. n = 2 returns [].

Constraints

  • 1 <= n <= 9

Follow-up

How would you count the number of valid boards without constructing every board string, and why is that usually faster?

Examples
Example 1
Input: n = 1
Output: [["Q"]]
Example 2
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Example 3
Input: n = 2
Output: []
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.