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.. "]
Has you met this question in a real interview? Analysis:how to determine whether the current position on jth row is valid? Suppose jth row position is place[j] and ith row position is place[i]. Then we found this place[i] leads three positions at jth row invalid. They is place[i], place[i]+j-i, place[i]-(j-i). Solution:
1 Public classSolution {2 PublicList<string[]> Solvenqueens (intN) {3list<string[]> res =NewArraylist<string[]>();4 int[] Place =New int[n];5Arrays.fill (place,-1);6 intLevel = 0;7 8 while(Level!=-1){9 if(level>=N) {Ten constructres (place,res,n); Onelevel--; A Continue; - } - the intval =Place[level]; -val++; - while(val<N) { - Booleanvalid =true; + for(inti=0;i<level;i++) - if(Val==place[i] | | val==place[i]+level-i | | val==place[i]-(level-i)) { +valid =false; A Break; at } - if(valid) Break; - Elseval++; - } - - if(val<N) { inplace[level]=Val; -level++; to}Else { +Place[level]=-1; -level--; the } * } $ Panax Notoginseng returnRes; - the } + A Public voidConstructres (int[] Place, list<string[]> Res,intN) { the Char[] line =New Char[n]; +Arrays.fill (line, '. ')); -string[] Oneres =NewString[n]; $ for(inti=0;i<n;i++){ $ intval =Place[i]; -line[val]= ' Q '; -String Linestr =NewString (line); theLine[val]= '. '; -oneres[i]=Linestr;Wuyi } the Res.add (oneres); - } Wu}
Leetcode-n-queens