DFS:N皇后

#include "cstdio"
#include "algorithm"
#include "iostream"
#include "string.h"
#include "math.h" 
using namespace std;
//N皇后
int n,tot=0;
int col[12]={0};
bool check (int c,int r){            //检查是否与以放好的皇后冲突 
    for (int i = 0; i < r ; i++)
        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;                //在第 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 (~scanf ("%d",&n)){
        if (n==0)
        return 0;
     cout<<ans[n]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AChappy/p/11959868.html