[Leetcode] n-Queens II

Source: Internet
Author: User

Question: given an integer N, it indicates that the size of the Board is N * n, and N queens are placed on the board. The same row, column, and diagonal lines cannot have the same queen, find the number of feasible solutions

Algorithm: Deep Priority Search + pruning Optimization

The pruning optimization scheme is as follows (take queen 4 as an example ):

It is not difficult to find the following rules:

The same left diagonal line: Row-Col + n = constant
The same right diagonal line: Row + Col = constant value

public class Solution {    final int CHECK_NUMBER = 3;  // check tree points: col, left diagonal and right diagonal    final int MAX_NUMBER = 1024;        int nSolutions = 0;boolean[][] isVisited = new boolean[CHECK_NUMBER][MAX_NUMBER];public int totalNQueens(int n) {        for (int i=0; i<CHECK_NUMBER; ++i) {        isVisited[i] = new boolean[MAX_NUMBER];        }                dfs(0, n);        return nSolutions;    }/** * boolean[0][MAXN]: * * 0: check the col * 1: check the left diagonal * 2. check the right diagonal *  */public void dfs(int row, int nGirds) {if (row == nGirds) {++nSolutions;return ;}for (int col=0; col<nGirds; ++col) {if (!isVisited[0][col]  && !isVisited[1][row-col+nGirds] && !isVisited[2][row+col]) {isVisited[0][col] = true;isVisited[1][row-col+nGirds] = true;isVisited[2][row+col] = true;dfs(row+1, nGirds);isVisited[0][col] = false;isVisited[1][row-col+nGirds] = false;isVisited[2][row+col] = false;}}}}

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.