P1219 eight queens

This problem is a classic USACO dfs, and the time I met at least seven months.

 Placing n queens on the chessboard n * n, they can not eat each other (rows, columns, diagonals), and asked several pendulum method? Think of the dfs (self do not think there are pictures of the DP). Well, first determine to enumerate is the i-th row, the boundary is searched row n + 1, j-th column next cycle to determine if I could take, if you can put this point to put the same row and column marked with the same mark, and then continue search, back, erase the mark. Here we want to set up a two-dimensional marking flag, flag [1] [j] = 1, flag [2] [i + j] = 1, flag [i-j + n] = 1

1.dfs enumerate what make it clear, in this case only the rows and columns can be solved, so just hold gold on the line or column

2. diagonal representation: x + y is the same as the lower left to the upper right, xy is the same as the lower right to get

3. Consider then the time complexity of a direct hit to the point mark, do not see a bool flag can not continue, so slow

Code

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<cmath>
 7 using namespace std;
 8 int a[50];
 9 int flag[50][50];
10 int n;
11 int cnt=0;
12 void dfs(int i){//枚举到了第i行
13     if(I> n-) { // end 
14          CNT ++ ;
 15          IF (CNT <= . 3 ) {
 16              for ( int I = . 1 ; I <= n-; I ++) { // each automatically updated 
. 17                  COUT << A [I] << "  " ;
 18 is              }
 . 19              COUT << endl; 
 20 is          }    
 21 is      return ;
 22 is      }
 23 is      for ( int J = . 1 ; J <= n-; J ++ ) {
 24          IF (In Flag [1][j]==0&&flag[2][i+j]==0&&flag[3][i-j+n]==0){
25             a[i]=j;
26             flag[1][j]=1;
27             flag[2][i+j]=1;//对角线 
28             flag[3][i-j+n]=1;
29             dfs(i+1);
30             flag[1][j]=0;
31             flag[2][i+j]=0;
32             flag[3][i-j+n]=0;
33         }
34     }
35 }
36 int main(){
37     cin>>n;
38     dfs(1);
39     cout<<cnt;
40 }

 

Guess you like

Origin www.cnblogs.com/china-mjr/p/11284082.html