n皇后问题

#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
#include <vector>
#define INF 0x3f3f3f3f
#define LL long long

using namespace std;

int n, sum = 0;
int e[8][8];

int jugde(int deep, int r, int m){
if(e[deep][r] != 1)
return 0;
for( int i = 0; i < deep; i++){
for( int j = 0; j < n; j++){
if( e[i][j] == m ){
if(j == r)
return 0;
if(abs(deep - i) == abs(r - j)) //¶Ô½ÇÏß
return 0;
}
}
}
return 1;
}

void dfs(int deep, int m){
if( deep == n && m == 2)
dfs(0,3);
if( deep == n && m == 3)
sum++;
int i;
for( i = 0; i < n; i++ ){
if( jugde(deep, i, m) == 1){
e[deep][i] = m;
dfs(deep+1, m);
e[deep][i] = 1;
}
}
}
int main()
{
cin >> n;
for( int i = 0; i < n; i++ ){
for( int j = 0; j < n; j++ ){
cin >> e[i][j];
}
}
dfs(0,2);
cout << sum << endl;
//system("pause");
return 0;
}

原文地址:https://www.cnblogs.com/854594834-YT/p/8759470.html