Va 750-8 queens chess problem

Source: Internet
Author: User

Question: Calculate the eight queens that must pass through the designated time.

Analysis: search. Because eight queens only have 92 groups of solutions, they can calculate 92 groups of solutions directly, and then query and output the solutions.

Here I use bitwise operations to calculate the eight queens and reduce the amount of code.

First, consider the impact of a Queen. The relationship between the next attack and the last attack is as follows:

A queen will influence two oblique directions (from top to bottom );

The left oblique influences the next layer to move one to the left, and the right to move one to the right;

Therefore, we use bitwise representation for the three effects,

L, m, and R are in three situations, respectively. The bit representation of all the points that the Queen was able to attack;

If the I-th element is used, the three elements correspond to the following places:

L = (L | (1 <I) <1, M | (1 <I), (R | (1 <I)> 1;

Here I am the selected enumeration element. I can use the bit operation to find the final Available Bit (-P & P );

But it is troublesome to expand (because it is 2 ^ I, not I ).

Note: There are % 2D output numbers.

#include <iostream>#include <cstdlib>#include <cstdio>using namespace std;int  ans[92][9],temp[9];int  Count = 0;void dfs(int L, int M, int R, int d){if (d == 8) {Count ++;return;}for (int i = 0 ; i < 8 ; ++ i) {if (((L|M|R)&(1<<i)) == 0) {for (int j = 0 ; j < d ; ++ j)temp[j] = ans[Count][j];ans[Count][d] = i+1;dfs((L|(1<<i))<<1, M|(1<<i), (R|(1<<i))>>1, d+1);for (int j = 0 ; j < d ; ++ j)ans[Count][j] = temp[j];}}}int main(){Count = 0;dfs(0, 0, 0, 0);int t,x,y;while (~scanf("%d",&t)) while (t --) {scanf("%d%d",&x,&y);printf("SOLN       COLUMN\n");printf(" #      1 2 3 4 5 6 7 8\n\n");int count = 1;for (int i = 0 ; i < Count ; ++ i)if (ans[i][y-1] == x) {printf("%2d     ",count ++);for (int j = 0 ; j < 8 ; ++ j)printf(" %d",ans[i][j]);printf("\n");}if (t) printf("\n");}return 0;}

Va 750-8 queens chess problem

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.