052 - N-Queens II

Follow up for N-Queens problem.

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


static int Q; 
static int retcur;

int locok(char **queen, int cur, int b)
{
	int i,j;
	for(i = 0; i< cur; i++)
	    for(j = 0; j < Q; j++) {
		if (queen[i][j] == 'Q') {
			if (i == cur || j == b) return 0;
			if (abs(i - cur) == abs(j - b)) return 0;
		}
	    }
	return 1;
}

void x8q(char **queen, int cur)
{
	if (cur == Q) return;
	if (cur == Q - 1) {
		int i;
		for(i = 0; i < Q;i ++) {
			if (locok(queen, cur, i)) {
				queen[cur][i] = 'Q';
				retcur++;
				queen[cur][i] = '.';
			}
		}
	} else {
		int i;
		for(i = 0; i < Q; i ++) {
			if (locok(queen, cur, i)) {
				queen[cur][i] = 'Q';
			        x8q(queen, cur + 1);
				queen[cur][i] = '.';
			}	
		}
	}
}

int totalNQueens(int n) 
{
	int i, j;
	retcur = 0;

	char *queen[100] = {0};
	for (i = 0; i < n; i++) {
		queen[i] = (char *)malloc(sizeof(char) * n);
		memset(queen[i], '.', n);
	}

	Q = n;
	x8q(queen, 0);
	return retcur;
}


int totalNQueens(int n) 
{
	int ret[] = {0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712};
	if (n <= 13) return ret[n];
	return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值