【题目--33. 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.
n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。
给定一个整数n,返回所有不同的n皇后问题的解决方案。
每个解决方案包含一个明确的n皇后放置布局,其中“Q”和“.”分别表示一个女王和一个空位置。
【样例】
对于4皇后问题存在两种解决的方案:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
【解题思路】
深度遍历+回溯。
1. 从上到下,从左到右,判断某个位置是否可以放皇后,可以放,转2,不可以,转3;
2. 放置皇后,并判断是否已经放置N个皇后,如果是,记录结果并回溯;否则转1,递归判断下一行能否放置皇后;
3. 判断本行下一列是否可以放置皇后。如果本列无法放置皇后,剪枝;否则查看下一列能否放置皇后。即,可以放置,就往下找;放不了,就往回看,拜托上层变一变,看能不能继续往下找,直到第一层都试过最后一列的位置,程序结束。
由于需要记录所有可行结果并输出,在每次得到可行结果时,将当前结果保存,并将Q还原为".",方便回溯。
【AC代码】
class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
//判断位置(row, col)是否可以放置皇后
bool judgeQ(vector<string> &queen, int row, int col) {
int n = queen.size();
for (int i = 0; i < row; ++i) {
for (int j = 0; j < n; ++j) {
if (queen[i][j] == 'Q') {
if (i == row || j == col || abs(row-i) == abs(col-j))
return false;
}
}
}
return true;
}
//递归放置皇后
void placeQ(vector<string> &queen, vector<vector<string> > &res, int row, int col) {
int n = queen.size();
//超过棋盘大小,结束
if (row == n || col == n)
return;
//(row, col)处可以放置皇后
if (judgeQ(queen, row, col)){
queen[row][col] = 'Q';
//如果皇后放在最后一行,得到一个可行解,否则为中间状态
if (row == n-1) {
//将可行解入栈,将置为Q的位置恢复为.,回溯
res.push_back(queen);
queen[row][col] = '.';
return;
} else {
//中间状态,继续判断下一行是否可以放置皇后,如果下一行不可以放置,将该点还原,判断改行的下一列是否可以放置皇后
placeQ(queen, res, row+1, 0);
queen[row][col] = '.';
placeQ(queen, res, row, col+1);
}
} else {
//当前位置无法放置皇后,如果已经是该行的最后一列,表示当前行无法放置,返回;否则,尝试当前行的下一列
if (col == n-1)
return;
else
placeQ(queen, res, row, col+1);
}
}
vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<vector<string> > res;
if (n < 0)
return res;
int row = 0, col = 0;
string str(n, '.');
vector<string> queen(n, str);
placeQ(queen, res, row, col);
return res;
}
};
加上中间输出后,可以更加直观了解整个过程。
对于4皇后问题。
先将皇后放在(0, 0),
寻找row = 1时可以放置皇后的位置,得到(1, 2),
当前情况下, row = 2时无法放置皇后,(1, 2)还原,找到(1, 3)可以放置皇后,
继续判断当前情况下row = 2能否放置皇后,找到(2, 1),
尝试row = 3, 无法放置,(2, 1)还原,row=2无法放置,row=1已经放置在最后一列,没有可选位置,(0, 0)还原,尝试(0,1)。
【题目--34. N-Queens II】
![]()
![]()
![]()
根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。
只需要改变得到可行解时对结果的处理。不用将现有的结果保存,只需要用一个整数记录可行解的个数即可。
【AC代码】
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int res = 0;
if (n < 0)
return res;
int row = 0, col = 0;
string str(n, '.');
vector<string> queen(n, str);
placeQ(queen, n, res, row, col);
return res;
}
void placeQ(vector<string> &queen, int n, int &res, int row, int col) {
if (row >= n || col >= n)
return;
//当前位置可以放置皇后
if (judgeQ(queen, n, row, col)) {
queen[row][col] = 'Q';
//最后一行放置皇后,得到可行结果
if (row == n-1) {
++res;
queen[row][col] = '.';
return;
} else {
//中间行放置皇后,递归
placeQ(queen, n, res, row+1, 0);
queen[row][col] = '.';
placeQ(queen, n, res, row, col+1);
}
} else {
//当前位置不可以放置皇后
//当前行已经尝试至最后一列,回溯
if (col == n-1)
return;
else
placeQ(queen, n, res, row, col+1);
}
}
bool judgeQ(vector<string> &queen, int n, int row, int col) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (queen[i][j] == 'Q') {
if (i == row || j == col || abs(row-i) == abs(col-j))
return false;
}
}
}
return true;
}
};
因为只需要输出结果的数量,只对结果计数,不保存中间结果,可以使用一维数组queen记录皇后放置的位置,queen[i]表示第i行皇后所在的位置,遍历所有的可能,如果有可行解,记录结果的数量+1。具体代码如下:
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int res = 0;
if (n < 0)
return res;
int row = 0, col = 0;
//queen记录第k行皇后所放位置
vector<int> queen(n);
placeQ(queen, res, n, 0);
return res;
}
void placeQ(vector<int> &queen, int &res, int n, int k) {
if (k == n) {
++res;
return;
}
//尝试所有可以放皇后的位置
for (int i = 0; i < n; ++i) {
if (!judgeQ(queen, k, i))
continue;
queen[k] = i;
placeQ(queen, res, n, k+1);
}
}
bool judgeQ(vector<int> &queen, int row, int col) {
for (int i = 0; i < row; ++i) {
//同一列
if (queen[i] == col)
return false;
//同一条斜线
if (abs(i-row) == abs(queen[i]-col))
return false;
}
return true;
}
};