[LeetCode] N-Queens II

题目链接

int totalNQueens(int n) {
	int total = 0;
	if (n == 0)
	{
		return total;
	}
	
	int* place_queen = new int[n];
	for (int i = 0; i < n; i++)
	{
		place_queen[i] = -1;
	}

	int index = 0;

	while (index >= 0)
	{
		place_queen[index]++;
		if (place_queen[index] >= n)
		{
			place_queen[index] = -1;
			index--;
			if (index < 0)
			{
				break;
			}
			continue;
		}
		bool place_able = true;
		for (int i = 0; i < index; i++)
		{
			if (place_queen[index] == place_queen[i]
			 || place_queen[index] == (place_queen[i] + (index - i))
			 || place_queen[index] == (place_queen[i] - (index - i)))
			{
				place_able = false;
				break;
			}
		}
		if (place_able == true)
		{
			index++;
			if (index >= n)
			{
				total++;
				index--;
				place_queen[index] = -1;
				index--;
			}
		}
	}
	return total;
}

你可能感兴趣的:([LeetCode] N-Queens II)