鱼C论坛

 找回密码
 立即注册
查看: 1635|回复: 0

[技术交流] N皇后递归代码

[复制链接]
发表于 2019-4-6 21:58:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <iostream>
  2. #include <cstring>
  3. #define N 15
  4. using namespace std;
  5. int table[N] = {0};
  6. int count = 0;

  7. //x行, y列
  8. bool check(int x, int y)
  9. {
  10.     //行不用检察
  11.     for(int i=0; i<x; i++)
  12.     {
  13.         if(table[i] == y)
  14.             return false;
  15.         
  16.         if(table[i]+i == x+y)
  17.             return false;
  18.         
  19.         if(table[i]-i == y-x)
  20.             return false;
  21.     }
  22.     return true;
  23. }

  24. void dfs(int col, int n)
  25. {
  26.     if(col == n)
  27.     {
  28.         count++;
  29.         return;
  30.     }
  31.     for(int i = 0; i<n; i++)
  32.     {
  33.         if(check(col, i))
  34.         {
  35.             table[col] = i;
  36.             dfs(col+1, n);
  37.             //table[col] = 0;
  38.         }
  39.     }
  40. }

  41. int main(){
  42.     int n;
  43.     cin >> n;
  44.     dfs(0, n);
  45.     cout << count << endl;

  46.     return 0;
  47. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 13:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表