51. N-Queens
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..”]
]
题意
n皇后问题就是:在一个nxn的棋盘格上,n个皇后之间两两不能相互攻击。
n个皇后摆放在n*n的棋盘格中,使得横、竖和两个对角线方向均不会同时出现两个皇后。
每个解包含n行n列,其中Q代表皇后,.代表空位置
思路
通过回溯法遍历棋盘格每一行皇后的位置,当n个皇后都能找到合适的位置,回溯状态,继续找下一个位置。每行必有一个皇后。
状态的回溯不仅仅需要把状态为恢复,还需要将当前的皇后的位置从结果中弹出。见代码。
![]()
注意
如何快速的判断不合法的情况
对角线1:行+列 就是对角线1的坐标
对角线2:行-列+n-1 就是对角线2的坐标
代码
class Solution {
private:
//快速判断不合法的情况
//col[i]表示第i列被占用,dia1[i]表示第i对角线1被占用,dia2[i]表示第i对角线2被占用
vector<bool> col, dia1, dia2;
vector<vector<string>> res; //存储结果
// 尝试在一个n皇后问题中, 摆放第index行的皇后位置,结果都保存在row向量中
//row保存是各个行中皇后的位置,返回的结果是棋盘格格式,需要转换
void putQueen(int n , int index, vector<int> &row){
//index从0开始,等于n说明已经找到了n个满足条件的皇后位置。已经是一个解了
if( index == n ){
res.push_back( generateBoard(n,row) );
return;
}
for( int i = 0 ; i < n ; i ++ )
// 尝试将第index行的皇后摆放在第i列
if( !col[i] && !dia1[index+i] && !dia2[index-i+n-1] ){
//找到一个index[i]位置
row.push_back(i); //第index行的皇后放在第i个位置
col[i] = true;
dia1[index+i] = true;
dia2[index-i+n-1] = true;
putQueen(n, index + 1, row); //尝试去index+1行,去摆放皇后,一行一行的摆放我们的皇后
col[i] = false;
dia1[index+i] = false;
dia2[index-i+n-1] = false;
row.pop_back(); //将第i位置还回来,表示该行的皇后不放这个位置,继续后摆放
}
return;
}
//结果转换
vector<string> generateBoard( int n, vector<int> &row ){
assert( row.size() == n );
vector<string> board(n, string(n, '.'));
for( int i = 0 ; i < n ; i ++ )
board[i][row[i]] = 'Q';
return board;
}
public:
vector<vector<string>> solveNQueens(int n) {
res.clear();
//初始化
col = vector<bool>(n, false);
dia1 = vector<bool>(2*n-1, false);
dia2 = vector<bool>(2*n-1, false);
vector<int> row;
putQueen(n , 0 , row); //从0行开始放皇后位置
return res;
}
};