目录
题目描述:
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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
52. N-Queens II
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
这两个问题可以看成是一个问题,一个是要皇后与皇后之间不能互相攻击的具体解法,另一个则是要种数
算法描述:
采用递归的方式,每次在棋盘的当前行放下一枚皇后(枚举所有情况),若与前面行的皇后不构成相互攻击的情况,则递归处理下一行,直到处理完整个棋盘。
具体的使用一个大小为n的数组记录各行已经放置的皇后的位置,判断当前行皇后和之前皇后有没有冲突的方式,只需要判断其是否在一列(判断这n个位置是否相同),以及判断其是否在一条斜线上(判断两个皇后的位置(列位置)和索引(行位置)的各自差的绝对值是否相等)
关于两个问题的差距,一个在递归出口,利用上面所提到的大小为n的数组还原正确的解法,并将其保持在结果数组中;另一个只需要在递归出口将正确的解法数目加1即可。
//51
class Solution {
public:
vector<vector<string>> res;
vector<vector<string>> solveNQueens(int n) {
vector<int> Q(n);
Solve(Q,n,0);
return res;
}
void Solve(vector<int> &Q, int n, int c){
if(c == n){
vector<string> oneres(n,string(n,'.'));
for(int i = 0; i < n; i ++)
oneres[i][Q[i]] = 'Q';
res.push_back(oneres);
return;
}
for(Q[c] = 0; Q[c] < n; Q[c] ++)
if(safe(Q,n,c))
Solve( Q, n,c + 1);
}
bool safe(vector<int> &Q, int n, int c){
for(int i = 0; i < c; i ++)
if(Q[i] == Q[c] || abs(Q[i] - Q[c]) == abs(c - i))
return false;
return true;
}
};
//52
class Solution {
public:
int res = 0;
int totalNQueens(int n) {
vector<int> Q(n);
Solve(Q,n,0);
return res;
}
void Solve(vector<int> &Q, int n, int c){
if(c == n){
res ++;
return;
}
for(Q[c] = 0; Q[c] < n; Q[c] ++)
if(safe(Q,n,c))
Solve( Q, n,c + 1);
}
bool safe(vector<int> &Q, int n, int c){
for(int i = 0; i < c; i ++)
if(Q[i] == Q[c] || abs(Q[i] - Q[c]) == abs(c - i))
return false;
return true;
}
};