Using bit arithmetic to solve Queen's problem and Queen's variant problem

Source: Internet
Author: User

Problem Description: N Queen question or the following Queen variant: in a What is the number of 4 non-attacking cars placed in the 6*6 's chessboard? (Ali 2016 intern online written questions)
#include <iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>using namespacestd;intN,m,goal;intans,sum;voidDFS (intRowintLdintRdintSumintNow )////every call, the feasible position POS is calculated according to the row,ld,rd. Then traverse all POS locations. Ld<<1,rd>>1 represents the next line. Row+p, indicating that line P has been occupied//(Ld+p) <<1, (Rd+p) >>1 represents a conflict condition at the next line of the diagonal position after the row p is occupied. {     if(now>n)return; if(sum<m) {intpos=goal& (~ (ROW|LD|RD));//all possible locations//printf ("%d%d%d%d\n", pos,row,ld,rd);                          while(pos>0)//Traverse all the positions of the line                         {                               intp=pos& (-pos);//P is a position that can be placed, which is actually the right bitpos-=p; DFS (Row+p, (ld+p) <<1, (rd+p) >>1, sum+1, now+1); } DFS (Row,ld<<1,rd>>1, sum,now+1);//traverse the next line     }     Else++ans;}intMain () {scanf ("%d%d", &n,&m);//n = 6,m = 4 indicates that 4 queens are placed on the 6x6 boardGoal= (1<<n)-1;//goal represents all the positions in a row. //printf ("%d\n", goal);DFS (0,0,0,0,0); printf ("%d\n", ans); System ("Pause"); return 0;}

Results and Analysis:

See matrix67 Daniel's blog for details.

Using bit arithmetic to solve Queen's problem and Queen's variant 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.