Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Put eight queens on an 8×8 chess board so that they cannot attack each other. That is, no two queens can be in the same row, column, or diagonal line.
The typicalbacktrackingThe problem
Ideas:
Experiment with the placement, starting with the first row and then the next. (The nice thing here is that you don’t need to worry about rows, just columns and diagonals.)
I was obsessed with the problem of the first line. I directly passed the parameter 0 in the code. I was curious about how to control the change of the column in the first line.
(abs (column-column) =abs (row-row))
See the notes for details (read carefully, be sure to understand,)
#include<iostream> #include <math.h> #define N 8 using namespace std; int num=0; Int cur[8]; Int check(int n){// Pass in line for(int I =0; i<n; I++) {if (cur [I] = = cur [n] | | abs (n - I) = = abs (cur [n] - cur [I])) {/ / whether the location of the current place before and if placed in the same column or with inclined column return 0; } } return 1; } void putQueen(int n){if(n== n){void putQueen(int n){if(n== n){void putQueen(int n){if(n== n){ }else{ for(int j=0; j<N; J ++){// place the column position from 0 to last. PutQueen (n+1); putQueen(n+1); putQueen(n+1); }}}} int main(){putQueen(0); cout<<num; return 0; }Copy the code