【算法刷题】8皇后问题

利用一个8个元素数组:queen[i]表示第i行的皇后所在列数;

8个元素只能从0-7中选择,每个只能一次,这就保证了皇后不处在同一列或同一行,

对于不处对角:任意两行的皇后i、j,不在对角满足|i-j|!=|queen[i]-queen[j]|

由此,可解题:queen数组的全排列,对于全排列中每一个可能性,判断不在对角的条件


//8皇后问题
//全排列+逐个判断
int g_number = 0;
void Print(vector vec)
{
	int len = vec.size();
	for (int i = 0; i < len; ++i)
	{
		cout << "( " << i << "," << vec[i] << " )  ";
	}
	cout << endl;
}

bool Check(vector vec) 
{
	int len = vec.size();
	if (len < 2)
		return false;

	
	for (int i = 0; i < len; ++i)
	{
		for (int j = i + 1; j < len;++j)
		{
			int row = abs(i - j);
			int col = abs(vec[i] - vec[j]);

			if (row == col)
				return false;
		}
	}

	return true;
}

//全排列递归
void quanpailie(vector& vec,int number)
{
	int len = vec.size();
	if (len == 0)
		return;

	if (number == len)
	{
		if (Check(vec))
		{
			++g_number;
			Print(vec);
			
		}
		return;
		
	}
	else
	{
		for (int i = number; i < len;++i)
		{
			swap(vec[i], vec[number]);
			quanpailie(vec, number + 1);
			swap(vec[i], vec[number]);
		}
	}

}

void EightQueen()
{
	vector queen(8, 0);

	for (int i = 0; i < 8;++i)
	{
		queen[i] = i;
	}
	quanpailie(queen,0);
}

int main()
{
	EightQueen();
	cout << "The total number is:" << g_number << endl;
}

你可能感兴趣的:(算法题)