首页 > 其他分享 >lintcode: N-Queens

lintcode: N-Queens

时间:2022-12-01 19:05:00浏览次数:41  
标签:cur int lintcode solution back vector Queens 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.

class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
vector<vector<string> > res;

void dfs(vector<int> &solution,int n,int cur){
if(cur==n){
string str="";
for(int i=0;i<n;i++){
str+='.';
}
vector<string> vec;
for(int i=0;i<n;i++){
string tmp=str;
tmp[solution[i]]='Q';
vec.push_back(tmp);
}
res.push_back(vec);
return;
}

for(int i=0;i<n;i++){
solution.push_back(i);
bool ok=true;
for(int j=0;j<cur;j++){
if(i==solution[j]|| (cur+i)==(j+solution[j])|| (cur-i)==(j-solution[j])){
ok=false;
break;
}
}
if(ok){
dfs(solution,n,cur+1);
solution.pop_back();
}else{
solution.pop_back();
}
}


}

vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<int> solution;
dfs(solution,n,0);

return res;
}
};


标签:cur,int,lintcode,solution,back,vector,Queens,queens
From: https://blog.51cto.com/u_15899184/5903607

相关文章

  • lintcode:Permutations
    Givenalistofnumbers,returnallpossiblepermutations.ChallengeDoitwithoutrecursion.1.递归classSolution{public:/***@paramnums:Alistofi......
  • lintcode:Subsets
    Givenasetofdistinctintegers,returnallpossiblesubsets.ChallengeCanyoudoitinbothrecursivelyanditeratively?1.18sclassSolution{public:/**......
  • lintcode: Permutations II
    Givenalistofnumberswithduplicatenumberinit.Findalluniquepermutations.可以见我的博文​​全排列实现​​classSolution{public:/***@paramnu......
  • lintcode: Subsets II
    Givenalistofnumbersthatmayhasduplicatenumbers,returnallpossiblesubsets1.先排序;再按求Subsets一样的做法,只是添加前检查是否已经存在。耗时171mscla......
  • lintcode:Subarray Sum Closest
    Givenanintegerarray,findasubarraywithsumclosesttozero.Returntheindexesofthefirstnumberandlastnumber.ExampleGiven[-3,1,1,-3,5],retur......
  • lintcode: Sqrt(x)
    Implementintsqrt(intx).Computeandreturnthesquarerootofx.Examplesqrt(3)=1sqrt(4)=2sqrt(5)=2sqrt(10)=3ChallengeO(log(x))求非线性方程的解可以......
  • 51.N-Queens
    The n-queens puzzleistheproblemofplacing n queensonan nxn chessboardsuchthatnotwoqueensattackeachother.Givenaninteger n,return all......
  • N-Queens
    51.N-Queens https://leetcode.cn/problems/n-queens/ classSolution:defis_valid(self,path,x,y):"""给出现有的棋盘path,和位置(x,y),判断在(x,y)......