KatInterview

Construct Non-Conflicting Queens Configurations

Trees & GraphsModel answer
HardModel answerTrees & Graphsbacktrackingrecursiondepth-first-search

Last updated

Compute all possible configurations of n non-attacking queens on an n x n board using stateful depth-first search.

Given an integer n specifying the dimensions of an n × n grid, place n queens on the board such that no queen can attack any other.

In chess, a queen can move any number of squares horizontally, vertically, or diagonally. Thus, a placement is non-attacking if no two queens share a row, column, or diagonal.

Return every unique arrangement of the board that satisfies this condition.

  • Represent each configuration as a list of n strings.
  • Each string corresponds to a single row, where 'Q' denotes a queen and '.' denotes an open space.
  • The output can list the arrangements in any order.

Constraints:

  • 1 <= n <= 9

Example 1: Input: n = 4
Output:

[
 [".Q..",
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",
  "Q...",
  "...Q",
  ".Q.."]
]

Example 2: Input: n = 1
Output:

[["Q"]]

Hints

Hint 1

Since exactly one queen must go in every row, iterate through the board row by row rather than evaluating all n^2 positions at once.

Hint 2

How can you efficiently check if a candidate column or diagonal is already under attack in O(1) time?

Hint 3

Notice the properties of matrix indices: elements along the same main diagonal share the same difference (row - col), while elements on the same anti-diagonal share the same sum (row + col).