首页 > 其他 > 详细

LeetCode_51totalNQueens [N-Queens II]

时间:2014-07-23 18:13:56      阅读:352      评论:0      收藏:0      [点我收藏+]
#pragma warning(disable:4996)

#include <Windows.h>
#include <tchar.h>
#include <cstdio>

/*
	submit time : 1
	request :
		Follow up for N-Queens problem.

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

void Swap(int* data, int i, int j) {
	int temp = data[i];
	data[i] = data[j];
	data[j] = temp;
}

void totalNQueensRecursively(int& total, int* data, int length, int index) {
	if (index == length - 1) {
		bool bPossible = true;
		for (int i = 0; i < length; ++i) {
			for (int j = i + 1; j < length; ++j) {
				if (i - j == data[i] - data[j] || i - j == data[j] - data[i]) {
					bPossible = false;
					break;
				}
				if (!bPossible)
					break;
			}
		}
		if (bPossible)
			++total;
	}
	else {
		int vernier = index;
		while (vernier < length) {
			Swap(data, vernier, index);
			totalNQueensRecursively(total, data, length, index + 1);
			Swap(data, vernier, index);
			++vernier;
		}
	}
}

int totalNQueens(int n) {
	if (n == 0) return 0;
	if (n == 1) return 1;

	int total = 0;
	int* data = new int[n];
	for (int i = 0; i < n; ++i)
		data[i] = i;

	totalNQueensRecursively(total, data, n, 0);

	return total;
}

//===============Test================
void Test(int n) {
	int total = totalNQueens(n);
	printf("%d\n", total);
}

int _tmain(int argc, _TCHAR* argv[]) {
	Test(5);

	system("pause");
	return 0;
}



LeetCode_51totalNQueens [N-Queens II],布布扣,bubuko.com

LeetCode_51totalNQueens [N-Queens II]

原文:http://my.oschina.net/ITHaozi/blog/294195

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!