51. N-Queens
Last updated
Was this helpful?
Last updated
Was this helpful?
Then-queens puzzle is the problem of placingn_queens on an_n×_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 distinct board configuration of the n-queens' placement, where'Q'
and'.'
both indicate a queen and an empty space respectively.
Example:
Thoughts:
The number of columns is n
, the number of 45° diagonals is2 * n - 1
, the number of 135° diagonals is also 2 * n - 1
. When reach[row, col]
, the column No. is col
, the 45° diagonal No. is row + col
and the 135° diagonal No. is n - 1 + col - row
. We can use three arrays to indicate if the column or the diagonal had a queen before, if not, we can put a queen in this position and continue.
Optimization: Merge all arrays into one: only need one boo array flag for size 5*n - 1:n for col; 2n -1 for col + row -> diag; 2n - 1 for n - 1 - row + row for anti_diag.
Code: T: O(n^2) S: O(n)
Code: merged T: O(n^2) S: O(n)