All the chess-playing people know: The Queen can eat the other pieces on the horizontal, vertical and diagonal lines with no limit to the number of steps. How to put 8 queens on a chessboard (with 8 * 8 squares) so that none of them can be eaten! This is the famous question of the eight queens.
A queen Q (x, y) can be eaten by Queen Q (row,col) satisfying the following conditions
X=row (cannot have two queens in portrait)
Y=col (Landscape)
Col + row = y+x; (Oblique positive direction)
Col-row = Y-x; (Oblique opposite direction)
The eight Queens question is illustrated in the data structure book, and we use the idea of backtracking. Because each row can only be a queen, so we recursive each row, and then loop the queen in each column of the case, if the above eight Queen's condition, then put the Queen in this place, recursive next line, know put on the last line.
Because the subject is to choose the first situation, so we have to record 92 cases in advance, this can save a lot of time.
#include <stdio.h> #include <string.h>int data[100][8]={0};int tmp[8]={0};int count;int valid (int x,int y) { int j;for (int i=0;i<x;i++) {j=tmp[i];if (j==y) return 0;if (i==x) return 0;if ((j+i) = = (X+y)) return 0;if ((y-x) = = (J-i)) return 0;} return 1;} void Copy () {for (int i=0;i<8;i++) data[count][i]=tmp[i]+1;} void process (int ind) {for (int i=0;i<8;i++) {if (valid (Ind,i)) {tmp[ind]=i;if (ind==7) {copy (); Count++;return;} Process (ind+1); tmp[ind]=0;}}} int main () {count=0;process (0); int n,m;scanf ("%d", &n), while (n--) {scanf ("%d", &m); for (int i=0;i<8;i++) printf ("%d", Data[m-1][i]);p rintf ("\ n");}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nine degrees 1140-backtracking-eight queens