N Queen's question
The eight Queens question, an old and famous problem, is a typical case of backtracking algorithms . The issue is the international chess player Max Bessel in 1848: Put eight queens on the 8x8 chess, so that they can not attack each other, that is, any two queens can not be in the same row, the same column or the same slash, ask how many kinds of pendulum . Gauss thinks there are 76 kinds of schemes. In 1854, in the Chess magazine in Berlin, different authors published 40 different solutions, and later some of them solved 92 kinds of results using the method of graph theory. , thus evolving the N Queen question:
Here are two ways to solve the N queen:
First way: DFS direct search
Code:
<span style= "FONT-SIZE:18PX;" ><strong> #include <iostream> #include <cstdio> #include <cmath>using namespace Std;int x[ 100],n,sum;int Ans[100];bool Place (int k)//Determine if the K queen can join {for (inti=1; i<k; i++) {if (X[i]==x[k] | | ABS (K-I ) ==abs (X[k]-x[i])) return false; } returntrue;} The initial value of void DFS (int k)//k is 1{if (k>n)//arranges N Queens after sum++ {sum++;//printf ("sum =%d\n", sum);//For (int i=1; i<=n; i++)//printf ("%d", x[i]);//printf ("\ n"); return; } else {for (int i=1; i<=n; i++)//Find the column coordinates of the K-Queens {x[k]=i; if (place (k)) {//printf ("%d", x[k]); DFS (k+1); }}}}int Main () {while (scanf ("%d", &n)!=eof && N) {if (Ans[n]) printf ("%d\n", a Ns[n]); else {DFS (1); Ans[n] = sum; printf ("%d\n", Ans[n]); }} return 0;}</strong></span>
The second way: do not understand, it should be a bit operation, do not understand the design process.
<span Style= "FONT-SIZE:18PX;" ><strong> #include <stdio.h> #include <stdlib.h>int ans[20];long sum = 0, Upperlim = 1; void test (long row, long ld, Long Rd) {if (row!= upperlim) {Longpos = Upperlim & ~ (Row | ld | rd); while (POS) {long p = pos &-pos; pos-= p; Test (Row + p, (ld + P) << 1, (rd + P) >> 1); }} else sum++;} int main () {int n; for (Inti=1; i<=20; i++) Ans[i] =-1; while (scanf ("%d", &n)! = EOF, N) {if (Ans[n]! =-1) printf ("%d\n", Ans[n]); else {sum = 0; Upperlim = 1; Upperlim = (Upperlim << n)-1; Test (0, 0, 0); Ans[n] = sum; printf ("%d\n", sum); }} return 0;} </strong></span>
<dfs Search > N Queens question