您的位置:首页 > 产品设计 > UI/UE

116. N-Queens

2016-07-06 08:40 411 查看
-51. N-Queens QuestionEditorial Solution My Submissions

Total Accepted: 57241

Total Submissions: 215678

Difficulty: Hard

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.

For example,

There exist two distinct solutions to the 4-queens puzzle:

思路:深搜+剪枝

class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<int> vis(n,0),resid(n,0);
vector<string> vs;
solveNQueens2(n,res,resid,vs,vis,0);
return res;
}
void solveNQueens2(int n,vector<vector<string>> &res,vector<int> resid,vector<string> vs,vector<int> vis,int j) {
if(j==n){
res.push_back(vs);
}
else{
string s(n,'.');
for(int i=0;i<n;++i){
if(vis[i]==0){
vis[i]=1;
s[i] = 'Q';
resid[j]=i;
if(!isLegal(resid,j,i)){
s[i] = '.';
vis[i]=0;
continue;
}
vs.push_back(s);
solveNQueens2(n,res,resid,vs,vis,j+1);
vs.erase(vs.end()-1);
s[i] = '.';
vis[i]=0;
}
}
}
}
bool isLegal(const vector<int> &resid,int row,int col)
{
for(int i=0;i<row;++i){//是否在同一对角线上
if(abs(col-resid[i])==abs(row-i))return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: