Leetcode 52.n-queens II (N Queen Problem II) thinking and method of solving problems

Source: Internet
Author: User

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

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.