回溯法--n后问题

问题描述

在一个n*n的棋盘上放置彼此不受攻击的n个皇后,按照国际象棋规则,皇后可以攻击与其在同一行,同一列或者同一对角线的其他皇后,求合法摆放的方案数。
输入一行包含一个整数n。
输出一行一个整数代表方案数。

解决思路

  • 判断第i行方案是否可行,只需判断1~i行

代码实现

/*
2

0
*/
#include <iostream>
#include <cmath>
using namespace std;

const int N = 10;

int n;
int sum = 0;
int x[N];
//x[i]表示皇后i放在第i行的第x[i]列, sum表示可行方案数量

bool Place(int k)
{
	for(int j = 1; j < k; j ++ )
		if((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k]))
			return false;
	
	return true;
}

void BackTrack(int t)
{
	if(t > n) sum ++;
	else
	{
		for(int i = 1; i <= n; i ++ )
		{
			x[t] = i;
			if(Place(t))
				BackTrack(t + 1);
		}
	}
}

int main()
{
	cin >> n;

	BackTrack(1);

	cout << sum << endl;
    
	return 0;
} 
posted @ 2022-05-15 15:24  esico  阅读(122)  评论(0)    收藏  举报