八皇后(回溯法)

#include
#include
using namespace std;

int n = 8;
int total = 0;
int *c = new int[n];

bool is_ok(int row)
{
	for (int j = 0; j != row; j++)
	{
		if (c[row] == c[j] || row - c[row] == j - c[j] || row + c[row] == j + c[j])
			return false;
	}
	return true;
}

void queen(int row)
{
	if (row == n)
		total++;
	else
		for (int col = 0; col != n; col++) 
		{
			c[row] = col;
			if (is_ok(row))
				queen(row + 1);
		}
}

int main()
{
	queen(0);
	cout << total;
	return 0;
}

 

你可能感兴趣的:(八皇后(回溯法))