• 基础练习 2n皇后问题


     1 #include<iostream>
     2 #include<math.h>
     3 
     4 using namespace std;
     5 #define Len 1000
     6 
     7 int b[Len][Len];
     8 int a[Len]= {0};
     9 int c[Len]= {0};
    10 int count=0;
    11 int m;
    12 bool check(int n, int i, int k) {
    13     if(b[n][i] == 0){
    14         return false;
    15     }
    16     if(k==0) {
    17         for(int j=0; j<n; j++) {
    18             if( a[j] == i || fabs(n-j) == fabs(a[j] - i)) {
    19                 return false;
    20             }
    21         }
    22     } else {
    23         for(int j=0; j<n; j++) {
    24             if(c[j] == i || fabs(n-j) == fabs(c[j] - i)) {
    25                 return false;
    26             }
    27         }
    28     }
    29     return true;
    30 }
    31 
    32 
    33 void f2(int n) {
    34     if(n==m) {
    35         count++;
    36         return;
    37     }
    38 
    39     for(int i=0; i<m; i++) {
    40         if(check(n, i, 1)) {
    41             c[n]=i;
    42             f2(n+1);
    43         }
    44     }
    45 }
    46 
    47 void f(int n) {
    48     if(n==m) {
    49         f2(0);
    50 
    51         //count++;
    52         return;
    53     }
    54 
    55     for(int i=0; i<m; i++) {
    56         bool x = check(n, i, 0);
    57         if(x) {
    58             a[n]=i;
    59             b[n][i]=0;
    60             f(n+1);
    61             b[n][i]=1;
    62         }
    63     }
    64 }
    65 
    66 int main() {
    67 
    68     cin>>m;
    69     for(int i=0; i<m; i++) {
    70         for(int j=0; j<m; j++) {
    71             cin>>b[i][j];
    72         }
    73     }
    74     f(0);
    75     cout<<count;
    76 }
  • 相关阅读:
    tornado简单的验证码
    python分页和session和计算时间差
    初始tornado框架
    Jquery小实例
    DOM+Javascript一些实例
    Javascript
    CSS拾遗+技巧集合
    css样式基础
    KVM NAT网络模式配置
    Ultimate guide to learning AngularJS in one day
  • 原文地址:https://www.cnblogs.com/zhishoumuguinian/p/10009760.html
Copyright © 2020-2023  润新知