经典回溯问题~~~
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.
AC代码:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > res;
vector<string> sol;
//initialize the sol
string s = "";
for(int i = 0; i < n; i++)
s += ".";
for(int i = 0; i < n; i++)
sol.push_back(s);
backTracking(sol, n, 0, res);
return res;
}
// void print(vector<string> &sol){
// for(int i = 0; i < sol.size(); i++)
// cout << sol[i] << endl;
// }
void backTracking(vector<string>& sol, int n, int column, vector<vector<string> > & res){
if(column == n){ // no queen left
res.push_back(sol);
//print(sol);
return;
}
for(int row = 0; row < n; row++){
if(isSafe(row, column, n, sol)){
place(row, column, sol);
backTracking(sol, n, column + 1, res);
remove(row, column,sol);
}
}
return; //如果这一列的每一行都无法放一个Queen,就会自动return了。
}
bool isSafe(int row, int column, int n, vector<string> & sol){
for(int i = 0; i < n; i++){ //同行或同列
if(sol[row][i] == 'Q' || sol[i][column] == 'Q')
return false;
}
for(int i = row, j = column; i < n && j < n; i++,j++){ //对角线方向1
if(sol[i][j] == 'Q')
return false;
}
for(int i = row, j = column; i >= 0 && j >= 0; i--,j--){ //对角线方向2
if(sol[i][j] == 'Q')
return false;
}
for(int i = row, j = column; i < n && j >= 0; i++,j--){ //对角线方向3
if(sol[i][j] == 'Q')
return false;
}
for(int i = row, j = column; i >=0 && j < n; i--,j++){ //对角线方向4
if(sol[i][j] == 'Q')
return false;
}
return true;
}
void place(int row, int column, vector<string> & sol){
sol[row][column] = 'Q';
}
void remove(int row, int column, vector<string> & sol){
sol[row][column] = '.';
}
};
52. N-Queens II
52就是统计个个数,直接改一改好了。