N-Queens II

Source: Internet
Author: User
Question

Follow up for n-queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Method
Like the above method, the backtracking method is used, and the structure is basically the same. Only the number of returned results is required.
    public int totalNQueens(int n) {        int[] queenAtCol = new int[n];        int total = getNQueens(0, n, queenAtCol);        return total;    }    public List<String[]> solveNQueens(int n) {        List <String[]> list = new ArrayList<String[]>();        return list;    }private int getNQueens(int row, int n, int[] queenAtCol) {if (row == n) {return 1;} else {int tempSum = 0;for (int col = 0; col < n; col++) {if (isValid(row,col,queenAtCol)) {queenAtCol[row] = col;tempSum += getNQueens(row + 1, n, queenAtCol);}}return tempSum;}}private boolean isValid(int row, int col,int[] queenAtCol) {//row is valid.//column for (int i = 0; i < row; i++) {if (queenAtCol[i] == col) {return false;}}for (int i = 0; i < row; i++) {if (i + queenAtCol[i] == row + col) {return false;}}for (int i = 0; i < row; i++) {if (col - row == queenAtCol[i] - i) {return false;}}return true;}


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.