N-queens II
Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
Idea: Solve the problem, the problem will be solved, or that the problem is more simple.
The specific code is as follows:
public class Solution { int count = 0;public int totalnqueens (int n) {int[] x = new Int[n];queens (x, n, 0); return Coun t;} void Queens (int[] x,int n,int row) {for (int i = 0; i < n; i++) {if (check (x,n,row,i)) {//Judge legal x[row] = i;//Place queen on row row, column I if ( row = = n-1) {///If it is the last row, the output COUNT++;X[ROW] = 0;//backtracking, looking for the next result return;} Queens (x, N, row+1);//Looking for the next line x[row] = 0;//backtracking}}}/** * @param x Array Solution * @param n Checkerboard Width * @param index currently placed row * @param i currently place column * @r Eturn */boolean Check (int[] x,int n,int row, int col) {for (int i = 0; i < row; i++) {if (x[i] = = Col | | x[i] + i = = col + Row | | X[i]-i = = Col-row) return false;} return true;}}
Trick: This problem has a very simple solution, do not look at the following code can you think of it?
—————————————————————————————
The code is as follows:
public class Solution {//Checkerboard width within 10 all results int[] x = new int[]{0,1,0,0,2,10,4,40,92,352,724};p ublic int totalnqueens (int n) {return x[n];}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 52.n-queens II (N Queen Problem II) thinking and method of solving problems