C ++ implements the n queen problem

Source: Internet
Author: User

// Reference books: Computer Algorithm basics-the third edition of Huazhong University of Science and Technology

// Use the backtracking method to implement the n queen problem. The nqueens (int K) method is implemented recursively. To improve efficiency, it can be changed to non-recursion.

//queen.h--Queen class#ifndef _QUEEN_H_#define _QUEEN_H_#include<iostream>class Queen{private: int queens;//total queens int *answer;//answer array  int sum;//total answers //judge a certain place is available,k represent row,i represent column bool place(int k,int i)const; void printResult()const;//print resultpublic: Queen(int n); ~Queen(); void nqueens(int k=1);//search the solutionof vector space under the condition  void printSum()const{ std::cout<<sum<<std::endl;}};#endif//N_QUEEN.cpp--Queen class methods#include<cmath>#include"queen.h"Queen::Queen(int n){ queens=n; answer=new int[n+1]; sum=0;}Queen::~Queen(){ delete []answer; }void Queen::nqueens(int k){ answer[k]=1; while(answer[k]<=queens) {  if(place(k,answer[k]))  {   if(k==queens)   {    sum++;    printResult();   }   else    nqueens(k+1);  }   answer[k]=answer[k]+1; }}bool Queen::place(int k,int i)const{ int m=1; while(m<k) {  if(answer[m]==answer[k]||abs(answer[k]-answer[m])==abs(k-m))   return false;  m++; } return true;}void Queen::printResult()const{ for(int i=1;i<queens;i++) {     std::cout<<answer[i]<<"  "; } std::cout<<std::endl;}//use.cpp--test Queen class#include<iostream>#include"queen.h"int main(){ std::cout<<"Enter the queens:"; int m; std::cin>>m; Queen q=Queen(m); q.nqueens(); std::cout<<"Total methods: "; q.printSum(); std::cout<<"Done!\n"; return 0;}

 

 

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.