N_Queen_DFS

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <ctime>
 4 #include <windows.h>
 5 int ans,N;
 6 int map[16][16];
 7 bool isCorrect(int row,int col)
 8 {
 9     for(int i=0;i<row;i++)
10         if(map[i][col]==1)
11             return false;
12     for(int j=0;j<col;j++)
13         if(map[row][j]==1)
14             return false;
15     for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
16         if(map[i][j]==1)
17             return false;    
18     for(int i=row+1,j=col-1;i<=N-1&&j>=0;i++,j--)
19         if(map[i][j]==1)
20             return false;
21     return true;
22 }
23 
24 void Dfs(int n,int col)
25 {
26     if(col==N)
27         {
28             ans++;
29             return;
30         }
31     for(int i=0;i<n;i++)
32         {
33             map[i][col]=1;
34             if(isCorrect(i,col))
35                 {
36                     Dfs(N,col+1);
37                 }
38             map[i][col]=0;
39         }
40     return;
41 }
42 
43 
44 int main()
45 {    
46     while(~scanf("%d",&N))
47         {
48             time_t start=clock();
49             ans=0;
50             memset(map,0,sizeof(map));
51             Dfs(N,0);
52             printf("Time: %ld Ms\n",clock()-start);
53             printf("Ans of %d Queen is %d\n",N,ans);
54             
55         }
56     system("pause");
57     return 0;    
58 }

 

 

 

posted @ 2013-06-20 15:56  瓶哥  Views(104)  Comments(0Edit  收藏  举报