面试题 08.12. 八皇后
冲突判断,对应当前row和col只需要判断是否和已存在的queen位置是否冲突
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> queen_pos;
vector<string> one_row_res(n, string(n, '.'));
vector<vector<string>> res;
inner(n, 0, queen_pos, one_row_res, res);
return res;
}
void inner(int n, int idx_i, vector<int>& queen_pos, vector<string>& one_row_res, vector<vector<string>>& res){
if(idx_i==n)
{
res.push_back(one_row_res);
return;
}
for(int j=0;j<n;j++)
{
if(valid(queen_pos, idx_i, j))
{
one_row_res[idx_i][j] = 'Q';
queen_pos.push_back(j);
inner(n, idx_i+1, queen_pos, one_row_res, res);
queen_pos.pop_back();
one_row_res[idx_i][j] = '.';
}
}
}
bool valid(vector<int>& queen_pos, int row, int col)
{
for(int i=0;i<queen_pos.size();i++)
{
if(i==row || col==queen_pos[i] || row+col==i+queen_pos[i] || row+queen_pos[i]==i+col)
return false;
}
return true;
}
};