zoukankan      html  css  js  c++  java
  • N皇后问题

    原题hdoj2553:

    题目描述:在一个N×N的方格中放置N个皇后,使其不能出现在同一列同一行同一对角线上,求有多少种放置方法。

    题目的思路还是和八皇后是一样的。唯一要注意的就是不能每次去找都要 dfs ,这样太消耗时间。因为n 的数据最多就到10,所以我们直接打个表存储就好了

    AC代码:

     1 #include <cstdio>
     2 #include <string>
     3 #include <iostream>
     4 #include <algorithm>
     5 #include <string.h>
     6 #include <math.h>
     7 
     8 using namespace std;
     9 
    10 const int maxn = 100;
    11 
    12 int vis[maxn];
    13 int cnt = 0;
    14 int n;
    15 
    16 bool check(int row,int col)
    17 {
    18     for (int i=0;i<row;i++)
    19     {
    20         if (vis[i] == col || abs(vis[i] - col) == abs(i-row))
    21             return false;
    22     }
    23     return true;
    24 }
    25 
    26 void dfs(int row)
    27 {
    28     if (row == n)
    29     {
    30         cnt++;
    31         return ;
    32     }
    33     else
    34     {
    35         for (int col = 0;col<n;col++)
    36         {
    37             if (check(row,col))
    38             {
    39                 vis[row] = col;
    40                 dfs(row+1);
    41             }
    42         }
    43     }
    44 }
    45 
    46 int main()
    47 {
    48     int a[11];
    49     for (n=1;n<11;n++)
    50     {
    51         dfs(0);
    52         a[n] = cnt;
    53         memset(vis,0, sizeof(vis));
    54         cnt = 0;
    55     }
    56     while (cin >> n){
    57         if (n == 0)
    58             return 0;
    59         else
    60             cout << a[n] << endl;
    61     }
    62     return 0;
    63 }
  • 相关阅读:
    [斜率优化][DP]luogu P3648 序列分割
    [状压DP]luogu P1879 玉米田
    [最短路][期望DP]luogu P1850 换教室
    [DP]JZOJ 3046 游戏
    [组合数学]JZOJ 3013 填充棋盘
    [贪心]JZOJ 3012 购买
    [最大流][二分]JZOJ 1259 牛棚
    [数学][构造]JZOJ 3317 管道
    Cookie和Session
    XSS和CSRF的理解
  • 原文地址:https://www.cnblogs.com/-Ackerman/p/11171898.html
Copyright © 2011-2022 走看看