Problem statement:
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.
For example,
There exist two distinct solutions to the 4-queens puzzle:[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]
Solution:
As a classical, N-Queens typically is a DFS problem. The solution follows DFS template.
According to the rules to place the queen, they can not in the same column, we do not need to keep a vector which records if a position is visited or not.
class Solution {public: vector> solveNQueens(int n) { vector > solu_sets; vector solu(n, string(n, '.')); NQueens(solu_sets, solu, 0, n, n); return solu_sets; }private: void NQueens(vector >& solu_sets, vector & solu, int row, int col, int n){ if(row == n){ solu_sets.push_back(solu); return; } for(int i = 0; i < col; i++){ if(isvalid(solu, row, i, n)){ solu[row][i] = 'Q'; NQueens(solu_sets, solu, row + 1, col, n); solu[row][i] = '.'; } } return; } bool isvalid(vector & solu, int row, int col, int n){ for(int i = row - 1, left = col - 1, right = col + 1; i >= 0; i--, left--, right++){ // vertically/diagonal/anti-diagonal conflict if(solu[i][col] == 'Q' || (left >= 0 && solu[i][left] == 'Q') || (right < n && solu[i][right] == 'Q')){ return false; } } return true; }};