Description:
Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
N Queen's question: Each of the two queens cannot be on the same row and the same slash. Find the number of solutions to the problem.
In order to reduce the two-dimensional problem to one dimension, it can be stored by a one-dimensional array, x[i] = J,i for rows, and J for columns. For any two queens, the constraints of the problem must be met, as is the conclusion:
|x[i]-x[k]|! = |i-k| && x[k]! = X[i] Meet this conclusion to be placed.
There is a classic backtracking method for this problem.
The algorithm will place the Queen in a row on the board until the eight queens are placed on the board without attacking each other, and the algorithm terminates. When a newly added queen cannot be placed on a chessboard because of an attack with an already existing queen, the algorithm goes back. Once this happens, you try to move the Queen that was last placed on the board to another place. This was done to allow the newly added queen to be placed in the proper position of the chessboard without attacking the other queens. Although the 7th Queen will not release an attack with any of the queens already placed on the chessboard, it will still need to be removed and traced back, as the 8th Queen cannot find a suitable position on the board.
Backtracking is a lot higher in overall performance than poor lifting method because it can be traced back in time after the discovery of the non-comprehension.
Code:
Public classSolution { Public int[] x;//Current Solution Public intSum//Number of solutions Public intN//Number of Queens Public intTotalnqueens (intN) { This. x =New int[n + 1]; for(inti=0; i<=n; i++) { This. x[i] = 0; } This. Sum = 0; This. N =N; BackTrack (1); returnsum; } Public voidBackTrack (intt) {if(T >n) {sum++; } Else { for(intI=1; i<=n; i++) { This. x[t] =i; if(place (t)) {BackTrack ( t+ 1);//Backtracking } } } } /*** Determine if the current position is legal*/ Public BooleanPlaceintk) { for(intJ=1; j<k; J + +) { if(Math.Abs (j-k) = = Math.Abs ( This. x[j]- This. x[k]) | | This. x[j] = = This. X[k]) { return false; } } return true; } }
Leetcode--n-queens II