The eight Queens question, that is, eight queens on the 8*8 lattice, requires each queen to be different rows, different columns, and no longer diagonal.
Solution One: full permutation solution. Eight queens do not walk, then assume that there is an array size of 8, the array subscript represents the row, 0~7 will be filled, the array of each subscript position of the value of the current queen's column, that is, the subscript value for the Queen's row, the array value represents the column. The subscript 0~7 must be different, and if you initialize the array with 0~7, the columns will be completely different. Then the column arrangement is 0~7 Eight number of full permutation problem, the rest is to judge is not on the diagonal, the specific code to achieve see: http://blog.csdn.net/moses1213/article/details/51055692
Solution Two: is also to set a length of 8 of the array, the value of each location of the array is the value of the column is judged, if it is valid to put up, that is, each subscript put 0~7, until the array each position on the legal value.
#include <iostream> #include <math.h> using namespace std; #define GRID_SIZE 8 bool Checkvalid (int* column, int row, int col) {for (int beforerow = 0; beforerow < row; ++before
Row) {if (column[beforerow] = = col) return false;
int columndistance = ABS (COLUMN[BEFOREROW]-COL);
int rowdistance = Row-beforerow;
if (columndistance = = rowdistance) return false;
return true;
} void Placequeen (int* column, int row) {static int count = 0;
if (row = = grid_size) {++count;
cout << "First" << count << "kind of Solution:";
for (int i = 0; i < grid_size ++i) {cout << column[i] << "";
if (i = = 7) cout << Endl; } else {for (int col = 0; col < grid_size; ++col) {if (Checkvalid (column, row, col)) {Column[row] =
Col
Placequeen (column, row+1);
}} void Queen8 () {int column[8];
Placequeen (column, 0);
int main () {//Your code goes here Queen8 ();
return 0; }