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