leetcode 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.
标准 DFS+回溯
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> a(n, string(n, '.'));
dfs(res, a, 0, n);
return res;
}
void dfs(vector<vector<string>>& res, vector<string>& a, int r, int n){
if(r==n){
res.push_back(a);
return ;
}
for(int i=0;i<n;i++){
if(!check(a,r,i,n))continue;
a[r][i]='Q';
dfs(res,a,r+1,n);
a[r][i]='.';
}
}
bool check(vector<string>& a, int r, int c, int n){
for(int i=0;i<r;i++)
if(a[i][c]=='Q')return false;
for(int i=r-1,j=c-1;i>=0&&j>=0;i--,j--)
if(a[i][j]=='Q')return false;
for(int i=r-1,j=c+1;i>=0&&j<n;i--,j++)
if(a[i][j]=='Q')return false;
return true;
}
};
可以用 flag 来精简一下 check
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> a(n, string(n, '.'));
vector<int> f1(n,1),f2(2*n-1,1),f3(2*n-1,1);
dfs(res, a, 0, n, f1, f2, f3);
return res;
}
void dfs(vector<vector<string>>& res, vector<string>& a, int r, int n, vector<int>& f1, vector<int>& f2, vector<int>& f3){
if(r==n){
res.push_back(a);
return ;
}
for(int i=0;i<n;i++){
if(f1[i]&&f2[r+i]&&f3[n-1+r-i]){
a[r][i]='Q';
f1[i]=f2[r+i]=f3[n-1+r-i]=0;
dfs(res,a,r+1,n,f1,f2,f3);
f1[i]=f2[r+i]=f3[n-1+r-i]=1;
a[r][i]='.';
}
}
}
};