N-queens II (Level 4 difficulty levels, superlative 5)
Follow up for n-queens problem.
Now, instead outputting board configurations, return the totalnumber of distinct solutions.
Answer:
The solution to the first question is similar, and the difference is that the return value of the DFS is the number of solutions. Every time we search our 8 locations,
Add the 8-position solution together. There is no solution to the position, its return value is 0.
Also note base case:
When row = = size, that is, row is out of bounds, this means that the whole n-queen is full, we should return the solution to 1. because
You do not need any action, that is, the only solution is to remain intact. (although a bit difficult to understand), students can back to the previous layer to think
For example, the last line, you put a queen, it is a solution, so where DFS to the next layer should return 1.
1 Public classSolution {2 Public intTotalnqueens (intN) {3 if(n = = 0) {4 return0;5 }6 7 //Bug 1:forget To modify the parameters of the function.8 returnDFS (n, 0,NewArraylist<integer>());9 }Ten One Public intDfsintNintRow, arraylist<integer>path) { A if(Row = =N) { - //The base case: When the last line, the Queen has only 1 ways of putting (or not putting) - return1; the } - - intnum = 0; - + //The Queen can select any of the slot. - for(inti = 0; I < n; i++) { + if(!isValid (path, i)) { A Continue; at } - Path.add (i); - - //All of the solutions is a possiablities is add up. -num + = DFS (n, row + 1, path); -Path.remove (Path.size ()-1); in } - to returnnum; + } - the Public BooleanIsValid (arraylist<integer> Path,intCol) { * intSize =path.size (); $ for(inti = 0; i < size; i++) {Panax Notoginseng //The same column with any of the current queen. - if(col = =Path.get (i)) { the return false; + } A the //diagonally lines. + //Bug 2:forget to add a ') ' - if(Size-i = = Math.Abs (Col-Path.get (i))) { $ return false; $ } - } - the return true; - }Wuyi}View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/totalNQueens_1218_2014.java
Leetcode:n-queens II Problem Solving report