Problem
The n-queens puzzle is the problem of placing n 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:
1 |
|
Explanation
-
We can use backtracking to solve this problem. First, create a
res
list, and acol[]
array has length equal to the number of row. Thecol[]
is used to store each row’s Queen’s column. From the above solution 1’s example, thecol[]
will becol[1, 3, 0, 2]
, which represents in first row, store the Queen in index1’s column; in second row, store the Queen in second row’s index3 column; in third row, store the Queen in the third row’s index0 column; in the fourth row, store the Queen in the fourth row’s index2 column. So, in thehelper
function, we passres
,col[]
, and the currentrow
as arguments. -
The base case is if the current row if it is greater than the board’s row number. If it is, then we translate
col[]
to a list of string (first string represents first row, second string represents second row, etc), then pass tores
becausecol[]
stores each row’s Queen column index. -
If the board has length $n$, then we loop $n$ times to try every column in each row. First, we try the first row that passed by the main caller’s function. So in the first row, we loop every column, and if it is valid, then we recursively call the next row.
-
To know if the column index we pass if it is valid, we need to create another function to check. For example, if we finish passing the first three rows
col[2, 0, 3, -]
, now we need to pass the fourth row’s Queen’s column index to the array. By the way, we don’t need to check row because each row only has one number. To check the column, we trycol[2, 0, 3, 0]
which is not valid because index1 also has 0; then we trycol[2, 0, 3, 1]
which is valid because before 1 is not present before. After checking column, we also need to check diagonal. We have the following statement: If two points’ row differences is equal to column difference, then these two points are in diagonal.
Solution
1 |
|