Queen eight's question (c Yan recursion implements backtracking)

Source: Internet
Author: User

The eight queens question is a question with the background of chess: how can we place eight queens on the 8x8 chess board, so that no queen can directly eat any other queen? For this purpose, neither queen can be in the same horizontal, vertical, or diagonal line. Now it is necessary to generate the total number of all feasible solutions, and generate the standard set by the Queen of every solution;


Generation of zookeeper parsing:

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <cstdlib>#define MAXN 8    //MAXN為最大皇后數,棋盤最大坐標#define RST(N)memset(N, 0, sizeof(N))using namespace std;int queen[MAXN], res = 0; //記錄皇后所在的縱坐標,方案個數void display()   //輸出一種可用方案所有皇后的坐標{    for(int i=0; i<MAXN; i++) {        printf("(%d, %d)", i, queen[i]);        i == MAXN-1 ? printf("\n") : printf(" ");    }    for(int i=0; i<55; i++) printf("~");    printf("\n");    res++;}bool check(int position) //判斷當前position之前的列是否能夠放置皇后{    for(int i=0; i<position; i++) {  //分別判斷當前列以及對角線是否有皇后佔用        if(queen[i] == queen[position] || abs(queen[i]-queen[position]) == (position-i)) return false;    }    return true;}void put(int position)  //回溯,繼續嘗試皇后所在行的位置,position為橫坐標喔{    for(int i=0; i<MAXN; i++) {        queen[position] = i;   //將皇后擺到當前行的不同列位置        if(check(position)) {            if(position == MAXN-1) display();  //全部擺好            else put(position+1);  //繼續擺放下一個皇后        }    }}int main(){    put(0);   //從初始位置進行擺放    printf("%d\n", res);   //輸出最後可行的方案總數    return 0;}


Queen eight's question (c Yan recursion implements 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.