N-queens
The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.
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 Indi Cate a queen and an empty space respectively.
For example,
There exist-distinct solutions to the 4-queens puzzle:
[ [". Q.. ", //solution 1 " ... Q ", " Q ... ",". . Q. "], ["]. Q. ", //Solution 2 " Q ... ", " ... Q ", ". Q.. "]
The Q[i] indicates that the position of the Queen placement of line I is illegal: q[i]==q[level]| | ABS (Q[level]-q[i]) ==abs (level-i)
1 classSolution {2 Public:3vector<vector<string> > Solvenqueens (intN) {4 5vector<int> Q (n,-1);6vector<vector<string> >result;7Getqueens (0, n,result,q);8 returnresult;9 }Ten One voidPrintqueens (vector<int> &q,vector<vector<string> > &result) A { - intn=q.size (); -vector<string>tmp; the stringstr; - for(intI=0; i<n;i++) - { -Str=""; + for(intj=0; j<n;j++) - { + if(Q[I]==J) str+='Q'; A Elsestr+='.'; at } - tmp.push_back (str); - } - - Result.push_back (TMP); - } in - voidGetqueens (intLevelint&n,vector<vector<string> > &result,vector<int> &q) to { + if(level==N) - { the Printqueens (q,result); * return; $ }Panax Notoginseng BOOLflag=false; - for(intI=0; i<n;i++) the { +q[level]=i; A if(IsValid (q,level)) the { +Getqueens (level+1, n,result,q); - } $q[level]=-1; $ } - } - the BOOLIsValid (vector<int> &q,int&Level ) - {Wuyi the for(intI=0; i<level;i++) - { Wu if(q[i]==q[level]| | ABS (Q[level]-q[i]) ==abs (level-i))return false; - } About $ return true; - } -};
"Leetcode" N-queens