Eight Queens Problem related C + + code solution Example _c language

Source: Internet
Author: User

The question of the eight Queens is the placing of 8 queens on a 8*8 board, which does not allow any two queens to be on the same line, the same column, and the same diagonal on the chessboard. Keywords: recursive, tracing. Common skills:
It was observed that a point a[i][j on a two-dimensional array of 8 x 8] (0<=i,j<=7)
The value of the i-j+7 of each point on the main diagonal (that is, the upper left to the lower right) (the range is (0,14)) is equal;
The value of the I+j (range (0,14)) of each point on the diagonal (i.e. upper right to left) is equal;
And the values of the i-j+7 between each main diagonal are different, and the values of each i-j+7 from the diagonal are different;
such as a[3][4]:
Main: 3-4+7=6
From: 3+4=7
So you can set two array b[15],c[15] to indicate whether the main, diagonal, or not is safe
(1 for the Queen, unsafe; 0 for security)

Each row has and has only one queen:
Every I queen placed in each I row (0<=i<=7)
void Eightqueens (int line);

Topic Description:
The chess-playing people know that the Queen can eat the other pieces on the horizontal, vertical and diagonal lines. How to put 8 queens on the Chessboard (8 * 8 squares) so that none of them can be eaten! This is the famous eight Queens problem.
For a 8 queen to meet the requirements of the placement method, define a queen string a corresponding to, that is, A=b1b2...b8, where bi is the corresponding pendulum in the number of the queen of the row in the column. Already know 8 queens problem A total of 92 groups of solutions (that is, 92 different queen strings).
Gives a number B, which requires the output of string B. The comparison of strings is such that the Queen string X is placed before the Queen string Y, and is smaller than y if and only when X is treated as an integer.
Input:
The 1th row is the number of groups n that test data, followed by the input of n rows. Each set of test data takes 1 rows, including a positive integer B (1 <= b <= 92)
Output:
Output has n rows, each output corresponds to one input. The output should be a positive integer, which is the Queen string corresponding to B.
Sample input:
2
1
92
Sample output:
15863724
84136275

Ideas
first put out an AC placement position to prevent people even the appearance of the chess board is not clear.

Since eight queens cannot be on the same line, it is certain that each Queen occupies one line. We can first define an array column[9], and the first number in the array represents the column number of the Queen in line I (because the array subscript starts at 0, so here you want to indicate that 1-8 needs to request 9 integer data spaces).
First initialize the column array to 1-8, ignoring the first element of the start
Next, do not repeat the entire arrangement for column, because we initialize the column with different numbers, so the eight queens are definitely in different columns.
Next, we only need to determine whether the eight queens are on the same diagonal, learned mathematics are known, can be expressed as Y = x + b or y =-H + b

#include <stdio.h> #include <stdlib.h> #include <string.h> #define EIGHT 8 struct result {int to
  Tal
int num[10];
 
};
int Wzyindex, column[10];
 
struct result results[100];
 
  /** * Description: Pretreatment of the Eight Queens Subscript array/void pre_prosess (int n) {int i;
  for (i = 1; I <= n; i + +) {Column[i] = i;
 
  }/** * Description:column array Digital exchange */void swap (int begin, int k) {int temp;
  temp = Column[begin];
  Column[begin] = column[k];
COLUMN[K] = temp;
  /** * Description: Prevent all permutations of duplicate data */int check_swap (int begin, int k) {int i;
    for (i = begin; I < K; i + +) {if (column[i] = = Column[k]) {return 0;
} return 1;
  int is_eightqueue (int n) {int i, J;  for (i = 1; I <= n; i + +) {for (j = i + 1; j <= N; j + +) {if (i-j = = Column[i]-Column[j] | | i-j = =
    COLUMN[J]-column[i]) return 0;
} return 1;
  } void Permutation_queue (int begin, int end) {int k, total; if (begin = = end) {//Check eight queen arrangement correctness if (Is_eightqueue (end)) {for (k = 1, total = 0; k <= end; k + +) {Total = $ total + Co
        LUMN[K]; 
      RESULTS[WZYINDEX].NUM[K] = column[k];
      } results[wzyindex].total = total;
    Wzyindex + +; } else {//all for (k = begin; K-<= end; k + +) {if (Check_swap (begin, K)) {//guaranteed no duplicates of all permutations of swap (
        Begin, K);
        Permutation_queue (begin + 1, end);
      Swap (begin, K);
  '} ' int compare (const void *p, const void *q) {Const struct result *a = p;
 
  const struct Result *b = q;
Return a->total-b->total;
  int main () {int i, n, M;
  Pre_prosess (eight);
  Wzyindex = 0;
  Permutation_queue (1, eight);
  Qsort (results, Wzyindex, sizeof (results[0)), compare);
      while (scanf ("%d", &n)!= EOF) {while (n-) {scanf ("%d", &m);
      M-= 1;
      for (i = 1; I <= eight i + +) {printf ("%d", results[m].num[i]);
    printf ("\ n"); }} return 0;
 }

/**************************************************************
    problem:1140
     User:wangzhengyi
    language:c
    result:accepted
 & nbsp;  time:10 Ms
    memory:916 KB
**************************************************** /
DFS mentality
is actually a DFS traversal, finding all combinations that meet the requirements, directly on the AC code

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define N 8 Type
def struct point {int x, y;} point;
 
Point Pts[n];
typedef struct STRING {char str[n + 1];} string;
 
String strs[93];
 
int Windex, Count;
 
  int isOk (int x, int y) {int i, flag = 1;
      for (i = 0; I < count i + +) {if (pts[i].y = y | | ABS (Y-PTS[I].Y) = ABS (x-pts[i].x)) {flag = 0;
    Break
} return flag;
 
  } void Bfseight (int level) {int i;
    if (Level > N) {for (i = 0; i < N; i + +) {Strs[windex].str[i] = pts[i].y + ' 0 ';
    } Strs[windex].str[i] = ';
  Windex + +;
    else {point T;
      for (i = 1; I <= N; i + +) {t.x = level;
 
      T.y = i;
        if (IsOk (T.x, T.y)) {Pts[count + +] = t;
        Bfseight (level + 1);
      Count = 1;
  int cmp (const void *p, const void *q) {const string *a = P;
 
  Const string *b = q; Return strcmp (A-&GT;str, B-&GT;STR);
 
  int main (void) {int n, num;
 
  Count = Windex = 0;
  Bfseight (1);
 
  Qsort (STRs, Count, sizeof (STRS[0)), CMP);
 
  scanf ("%d", &n);
 
    while (n-) {scanf ("%d", &num);
  printf ("%s\n", strs[num-1].str);
return 0;
 }

/**************************************************************
    problem:1140
     User:wangzhengyi
    language:c
    result:accepted
 & nbsp;  time:10 Ms
    memory:916 KB
**************************************************** /

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.