[面试] 八皇后的一位数组递归写法。第五次写了!难道还会忘么?

八皇后 : 的递归写法。用一维数组。没什么说的。。挺 easy~ 的。还有其他方法,以后再尝试吧!

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");

using namespace std;
const int N = 10;
int pos[N];
int num;
int cnt;
bool check(int n) {
	for(int i = 0; i < n; i++) {
		if(pos[i] == pos[n]) return false;
		if(abs(pos[n] - pos[i]) == n-i) return false;
	}
	return true;
}
void solve(int n) {
	if(n == num) {
		cnt++;
		return;
	}
	for(int i = 0; i < num; i++) {
		pos[n] = i;
		if(check(n)) {
			solve(n+1);
		}
	}
}
int main() {
	cin >> num;
	solve(0);
	printf("%d\n", cnt);
	return 0;
}

原文地址:https://www.cnblogs.com/robbychan/p/3787149.html