LeetCode N-Queens II

本文介绍如何解决N皇后问题并计算不同解决方案的数量。通过简化算法,仅关注解的数量,而不显示具体板配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

 

和上一题类似,只需要求解解的数量,简化一下就可以了,具体见上一题。

 

代码:

class Solution {
	int ans;		//结果
	vector<int> frows,fcols,frowcol,fcolrow;	//相应行有Q,列有Q,右下方向斜线有Q,右上方向斜线有Q
public:
    bool isValid(int row,int col,int n)	//判断相应位置是否可以插入Q
	{	
		if(frows[row]==1||fcols[col]==1)	//行有,列有Q
			return false;
		if(frowcol[row-col+n-1]==1)	//线x-y+n-1=i有Q
			return false;
		if(fcolrow[row+col]==1)	//线x+y=i有Q
			return false;
		return true;
	}
	void innerSolve(int row,int col,int n,int num)	//行、列、n、已经插入的Q数
	{
		if(num==n)
			ans++;
		else	//寻找之后所有可以插入的位置
		{
			int i,j;
			for(i=row;i<n;i++)
			{
				for(j=0;j<n;j++)
				{
					if(isValid(i,j,n))
					{
						frows[i]=1;
						fcols[j]=1;
						frowcol[i-j+n-1]=1;
						fcolrow[i+j]=1;
						innerSolve(i+1,0,n,num+1);	//递归求解
						frows[i]=0;
						fcols[j]=0;
						frowcol[i-j+n-1]=0;
						fcolrow[i+j]=0;
					}
				}
			}
		}
	}
	int totalNQueens(int n){
		ans=0;
		frows.clear();
		fcols.clear();
		frowcol.clear();
		fcolrow.clear();
		int i;
		for(i=0;i<n;i++)
		{
			frows.push_back(0);
			fcols.push_back(0);
		}
		for(i=0;i<2*n;i++)
		{
			frowcol.push_back(0);
			fcolrow.push_back(0);
		}
		innerSolve(0,0,n,0);	//求解
		return ans;
	}
};


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值