[Leetcode#51] N-queens

Source: Internet
Author: User

problem:

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.. "]

Analysis:

This isA very very typical DFS and back tracking problem!!! but for  Thisspecific problem, we could sovle it with a magic skill, which could greatly save the space complexity and time comple Xity. Typical thinking:during The search process, weTryTo place a queen onto a position (I, j) and then we check ThisPlacement Againt All and placements, so asTo make sure EThe current placement isvalid. The instant idea for  This  is "Check the new placement againt all girds before it". Since the Borad isA"N*n"Matrix, we have the use O (n^2) time complexity of checking a single placement. but Thisproblem could be elegantly solved by following observation:since we are only having one queue at each row, why not we just Record each row's Queen'S column index?Why should we care is about the empty space, since we actually never use them. Great!!!! haha!Step1: Compress the sparse matrix into an array.int[] placed =New int[n]; Note:placed[i] denotes the There isqueue at (I, placed[i]). Step2: Define a properBase  Case! At here, only when a path isValid, we allow it to go deeper! Thus we don't need to worry if the placement are legal when we just reach the next level. (We just need to use typical pos-to-check IFF We have already place all queens properly)----------------------------------------------------if(pos = =N) {List<String> item =NewArraylist<string> ();  for(inti =0; I < n; i++) {String row="";  for(intj =0; J < N; J + +) {            if(Placed[i]! =j) Row+="."; ElseRow+="Q";    } item.add (row); } ret.add (item);} Note:the result Recover Process isVery very interesting~~~powerful~~~haha!Step3: How to checkifA placement isValid?We Check the current placement against all previous placement (only queens) for(inti =0; i < row_no; i++) {    if(Col_no = = Placed[i] | | (Math.Abs (col_no-placed[i]) = = Row_no-i))return false;} Note:since we use a array of recording our placement information, we DoNot need to recover the state ( forOther placements at the same level) for(intj =0; J < N; J + +) {    if(IsValid (placed, POS, j)) {Placed[pos]= J;//Other placement would automatically override Placed[pos]Helper (placed, N, pos+1, ret); }}butifWe use the ArrayList, we need to DoState.add (i); .... State.remove (State.size ()-1);

Solution:

 Public classSolution { PublicList<list<string>> Solvenqueens (intN) {List<List<String>> ret =NewArraylist<list<string>> (); if(N <=0)            returnret; int[] placed =New int[n]; Helper (placed, N,0, ret); returnret; }            Private voidHelperint[] placed,intNintPOS, list<list<string>>ret) {        if(pos = =N) {List<String> item =NewArraylist<string> ();  for(inti =0; I < n; i++) {String row="";  for(intj =0; J < N; J + +) {                    if(Placed[i]! =j) Row+="."; ElseRow+="Q";            } item.add (row);        } ret.add (item); }         for(intj =0; J < N; J + +) {            if(IsValid (placed, POS, j)) {Placed[pos]=J; Helper (placed, N, POS+1, ret); }        }    }            PrivateBoolean IsValid (int[] placed,intRow_no,intcol_no) {         for(inti =0; i < row_no; i++) {            if(Col_no = = Placed[i] | | (Math.Abs (col_no-placed[i]) = = Row_no-i))return false; }           return true; }}

[Leetcode#51] N-queens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.