Skip to content

八皇后问题 ​

回溯加DFS ​

c++
八皇后
#include <iostream>
#include <stdio.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include<iomanip>
#include <string>
using namespace std;
int n, a[20], cnt = 0, ans = 0;
bool check(int x, int y)//判断是否能放
{
	for (int i = 1; i <= x; i++)
	{
		if (a[i] == y)
			return false;
		if (i + a[i] == x + y)
			return false;
		if (i - a[i] == x - y)
			return false;
	}
	return true;
}
void dfs(int row)
{
	if (row == n+1)//是否有解
	{
		ans++;
		if (cnt < 3)
		{
			cnt++;
			for (int i = 1; i <= n; i++)
			{
				cout << a[i] << ' ';
			}
			cout << endl;
		}
		return;
	}
	for (int i = 1; i <= n; i++)
	{
		if (check(row, i))
		{
			a[row] = i;//a[1]=1,a[2]=2
			dfs(row + 1);
			a[row] = 0;//回溯
		}
	}
}
int main()
{
	cin >> n;
	dfs(1);
	cout << ans;
	return 0;
}