HDU 2553 N Queen problem (backtracking)

Source: Internet
Author: User

Test instructions

The squares of the N*n (n <= 10) have placed n queens so that they do not attack each other (that is, any 2 queens are not allowed to be in the same row, in the same column, or in a diagonal line that is 45-angled to the checkerboard border. Your task is to find out how many legal placement methods are available for a given n.

Ideas:

Backtracking + pruning, a bit similar to DFS full arrangement. Use Emp[i] to represent the row from left to right for the first queen, so that all queens are not in the same column by default.

Code:

#include <cstdio>#include<iostream>#include<cstring>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>using namespacestd;Const intMAXN = at;intEMP[MAXN];//Emp[i] represents the row from left to right the first queenintUSED[MAXN];//Mark this line is already in useintN;intCnt//the total number of reasonable solutionsintCheckintKey//determine if the position of the first Queen is reasonable{    if(used[Emp[key])//Determine whether the row is reasonable        return 0;  for(inti =1; I < key; i++)//judging whether oblique and reasonable        if(ABS (i-key) = = ABS (Emp[i]-Emp[key])) return 0; return 1;}voidBacktrackintkey) {    if(Key > N)//a solution satisfying the conditioncnt++; Else    {         for(inti =1; I <= N; i++)//The Queen of the key column can have N options (states) placed on the 1-n line{Emp[key]= i;//Put the first key queen on line I            if(check (key))//legitimacy{Used[i]=1;//Mark this line is already in useBacktrack (key +1);//continue to solve the next queen .Used[i] =0;//Recovery Site            }        }    }}intMain () {//freopen ("OUT.txt","W", stdout);  while(Cin >>N) {cnt=0; memset (EMP,0,sizeof(EMP)); memset (Used,0,sizeof(used)); Backtrack (1);//start with the first Queen .    }    return 0;}

HDU 2553 N Queen problem (backtracking)

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.