The eight Queens question, an old and famous problem, is a typical case of backtracking algorithms. The issue is the international chess player, Max Bessel, in 1848: Put eight queens on the 8x8 chess game so that they don't attack each other.
Click, that is, any two queens can not be in the same row, the same column or the same slash, ask how many kinds of pendulum. Gauss thinks there are 76 kinds of schemes. In 1854, in the Chess magazine in Berlin, different authors published 40 different solutions, and later some of them solved 92 kinds of results using the method of graph theory. After the invention of computer, there are many computer languages to solve this problem. —————————— from the Encyclopedia of the mother of the
The eight Queens question is a very typical example of backtracking and search. The key to the algorithm is the matrix. If on the same line, the line number is the same (column above). If all are on the "/" diagonal, the rows and columns are the same, and if all are on the "\" diagonal, the row and column differences are the same.
We can search by behavior conditions, place a later set of diagonal and column numbers, just like the following program:
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <iomanip>5 using namespacestd;6 BOOLd[ -]={0},b[ -]={0},c[ -]={0};//defines an array of rows and columns, and a diagonal array. 7 intsum=0, a[ -];8 intSearchint);9 intprint ();Ten intMain () One { ASearch1);//computed with the search (int) function. - } - intSearchinti) the { - intJ; - for(j=1; j<=8; j + +) - if((!b[j]) && (!c[i+j]) && (!d[i-j+7])) + { -A[i]=j;//Place the Queen. Declares the rows, columns, and diagonals that are occupied. +b[j]=i; Ac[i+j]=1; atd[i-j+7]=1; - if(i==n) print ();//If the 8 queens are all set, output. - ElseSearch (i+1);//continue to place the Queen recursively, backtracking. -b[j]=0; -c[i+j]=0; -d[i-j+7]=0; in } - } to intprint () + { - inti; thesum++;//number of scenarios cumulative *cout<<sum<<Endl; $ for(i=1; i<=n;i++)//Output ScenariosPanax NotoginsengCOUT<<SETW (4) <<A[i]; -cout<<Endl; the}
The procedure is this:
Where "92" represents the scheme, the following number is the first column (rows are from one to eight)
Explain that is (1,8) (2,4) (3,1) (4,3) (5,6) (6,2) (7,7) (8,5)
To expand is to become the N Queen question:
#include <iostream>#include<cstdio>#include<cstdlib>#include<iomanip>using namespacestd;BOOLd[ -]={0},b[ -]={0},c[ -]={0};intsum=0, a[ -],n;//Notice there's an extra n. intSearchint);intprint ();intMain () {CIN>>n;//Enter N. Search1); }intSearchinti) { intJ; for(j=1; j<=n;j++) if((!b[j]) && (!c[i+j]) && (!d[i-j+n-1])) {A[i]=J; B[J]=i; C[i+j]=1; D[i-j+n-1]=1; if(i==N) print (); ElseSearch (i+1); B[J]=0; C[i+j]=0; D[i-j+n-1]=0; }}intprint () {inti; Sum++; cout<<sum<<Endl; for(i=1; i<=n;i++) cout<<SETW (4) <<A[i]; cout<<Endl;}
8 Queens and their popularity (N)-Sledgehammer (1)