N皇后问题(经典DFS)

N皇后问题

n个“皇后”,摆在一个n*n的棋盘里,要求任意两个不能互相攻击(同行、同列、同对角线可互相攻击)

求方案数

输入

n

输出

方案数

样例输入

8
样例输出

92

 思路详见代码注释

#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;

int n,tot=0;
int col[12] = {0};
bool check(int c,int r){   //检查冲突  在(r,c)这个点
    for(int i=0 ;i<r ;i++)             //0~r列
      if(col[i] == c ||(abs(col[i] - c) == abs(i-r)))   //这一列有数字||(列-列 = 行 - 行)
      return false;
    return true;
}

void DFS(int r){    //一行一行放,这是第r行
    if( r == n){    //所有皇后放好了
        tot++;
        return ;
    }
    for(int c =0; c<n ;c++)  //在每一列放皇后
       if(check(c,r)){       //检查合法
           col[r] = c;      //放下一行
           DFS(r+1);
       }
}

int main(){
    int ans[12] = {0};
    for ( n = 0; n <= 10; n++)
    {
     memset(col,0,sizeof(col));
     tot = 0;
     DFS(0);
     ans[n] = tot;
    }
    while(cin >> n){
        if(n ==0 )
        return 0;
        cout << ans[n] <<endl;
    }
    return 0;
    
}

 

posted @ 2020-08-29 21:26  Jesen等不等式  阅读(219)  评论(0编辑  收藏  举报