N_Queen_模拟位运算

用数组模拟的位运算,虽然模拟的很拙劣。。但是至少比普通搜索快1倍。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <ctime>
 4 #include <cstdlib>
 5 const int SIZE = 12;
 6 int sum=0,row[SIZE]={0},ld[SIZE]={0},rd[SIZE]={0};
 7 void L_m(int *a)
 8 {
 9     for(int i=0;i<SIZE-1;i++)
10         a[i]=a[i+1];
11     a[SIZE-1]=0;
12 }
13 void R_m(int *a)
14 {
15     for(int i=SIZE-1;i>0;i--)
16         a[i]=a[i-1];
17     a[0]=0;    
18 }
19 
20 void DFS(void)
21 {
22     int i,j;
23     for(i=0;i<SIZE;i++)
24         if(row[i]==0)
25             break;
26     if(i==SIZE)
27         sum++;
28     else
29         {
30             int flag[SIZE]={-1},p=0;
31             for(i=0;i<SIZE;i++)
32                 {
33                     if(!row[i] && !ld[i] && !rd[i])
34                         flag[p++]=i;
35                 }
36             if(p>0)
37                 {
38                     p--;
39                     while(p>=0)
40                         {
41                             row[flag[p]]=1;
42                             
43                             ld[flag[p]]=1;
44                             int L_n=ld[0];
45                             L_m(ld);
46                             
47                             rd[flag[p]]=1;
48                             int R_n=rd[SIZE-1];
49                             R_m(rd);
50                             
51                             DFS();
52                             
53                             row[flag[p]]=0;
54                             R_m(ld);
55                             ld[0]=L_n;
56                             ld[flag[p]]=0;
57                             
58                             L_m(rd);
59                             rd[SIZE-1]=R_n;
60                             rd[flag[p]]=0;
61                             
62                             p--;
63                         }
64                 }
65         }
66     return;
67 }
68 
69 int main()
70 {
71 
72     time_t start = clock();
73     DFS();
74     printf("Time: %ld Ms\n",clock()-start);
75    printf("ANS of %d Queue is %d\n",SIZE, sum);
76     system("pause>nul");
77     return 0;    
78 }

 

posted @ 2013-06-21 11:20  瓶哥  Views(161)  Comments(0Edit  收藏  举报