Leetcode: "L4" N-queens Problem solving report

Source: Internet
Author: User

"L4" N-queens Problem solving report


N-queens Total accepted:16418 Total submissions:63309 mysubmissions
The N-queens puzzle is the problem of placing n queens in an nxnchessboard such, that no, and Queens attack each other.



Given an integer n, return all distinct solutions to the n-queenspuzzle.

Each solution contains a distinct board configuration of Then-queens ' placement, where ' Q ' and '. ' Both indicate a queen a nd anempty 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 classic eight Queens question.
Solution 1:
< The difficulty level for this question is level-4>
Use DFS to solve.
Homepage June wrote two versions to solve.
The first version, after placing a queen, to find all possible placement points after a queen. This can be tested in eclipse, but
I can't go through Leetcode's inspection. That means the complexity is too high.
Solution 1
Solution 2:
Later, after checking the information, I learned that in order to speed up the search, we should think of this idea:
1. If we are going to place 8 Queens, the Queen will attack the peers, so 8 rows must be placed in a queen.
So the front page June from a queen has been searching to the end is not necessary. What we're going to do is: after placing the good one queen, search the next line
Can you put another queen, if not, you can return directly. This can save a lot of computational weight:



Homepage June code is as follows:
GitHub Code Links
December 17th, rewrite as follows:
1  Public classSolution {2      PublicList<string[]> Solvenqueens (intN) {3list<string[]> ret =NewArraylist<string[]>();4         5         if(n = = 0) {6             returnret;7         }8         9DFS (N,NewArraylist<integer>(), ret);Ten         returnret; One     } A      -      PublicString[] Createsolution (arraylist<integer>path) { -         /* the         [ -          [". Q.. ",//Solution 1 -           "... Q ", - "Q ...", +           ".. Q. "], -          +          [".. Q. ",//Solution 2 A "Q ...", at           "... Q ", -           ". Q.. "] -         ] -         */ -         intSize =path.size (); -string[] ret =NewString[size]; in          -          for(inti = 0; i< size; i++) { toStringBuilder SB =NewStringBuilder (); +              for(intj = 0; J < size; J + +) { -                 //a queen. the                 if(J = =Path.get (i)) { *Sb.append (' Q ')); $}Else {Panax NotoginsengSb.append ('. ')); -                 } the             } +              ARet[i] =sb.tostring (); the         } +          -         returnret; $     } $      -     //arraylist<integer> Path:store The index of the columns of one solution. -      Public voidDfsintN, arraylist<integer> Path, list<string[]>ret) { the         if(path.size () = =N) { -String[] Solution =createsolution (path);Wuyi Ret.add (solution); the             return; -         } Wu          -          for(inti = 0; I < n; i++) { About             //Judge If this is a solution; $             if(!isValid (path, i)) { -                 Continue; -             } -              A Path.add (i); + DFS (n, path, ret); thePath.remove (Path.size ()-1); -         } $     } the      the      Public BooleanIsValid (arraylist<integer> Path,intindex) { the         intSize =path.size (); the          for(inti = 0; i < size; i++) { -             //same column as one queen. in             if(Index = =Path.get (i)) { the                 return false; the             } About              the             //above the two diagonal lines the             //Bug 3: One less) the             if(Size-i = = Math.Abs (Index-Path.get (i))) { +                 return false; -             } the         }Bayi          the         return true; the     } -}
View Code

Steps:
1. Create a column value that ArrayList store the Queen for each row.
For example: The first line of the Queen in the third column, the second row of the Queen in the Fifth column, we will record 3,5 in the ArrayList, in turn push it down.
2. After entering DFS, first determine if the array is full or full, 8 queens are set, create a solution and return.
3. If it is not full, scan the current line for all positions and find out if you can put a queen. If it can be put, continue Dfs. If you can't put it, just quit.

Although the subject to understand the idea, it is not difficult to write, but the homepage June think the difficulty is: how can you think of a line to put the Queen? Instead of putting a good one on the next possible point? It's not hard to figure this out.
Level 4 is well-deserved.

Leetcode: "L4" n-queens problem solving report

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.