Two methods of solving eight queens problem eight queen

Source: Internet
Author: User

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;	 }


Related Article

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.