码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_51totalNQueens [N-Queens II]

时间:2014-07-23 18:13:56      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:os   io   for   re   c   ar   

#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]

标签:os   io   for   re   c   ar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!