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)