Nine degrees 1140-backtracking-eight queens

Source: Internet
Author: User

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

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.