剑指offer面试题38扩展:八皇后问题--递归解法

题目:在8*8的国际象棋上摆上8个皇后,使其不能互相攻击,即任意两个皇后不得处在同一行,同一列或者同一条对角线上。

思路:由于8个皇后不能处在同一行,那么肯定是每一个皇后占据一行。我们可以定义一个数组ColumnIndex[8],数组值表示第i行皇后的列号。先把数组用0-7初始化,然后对数组进行全排列。只需要判断每一个排列对应的8个皇后是不是在同一条对角线上也就是对于数组的两个下标 i 和 j ,是否有 i-j == Columnindex[i] - Columnindex[j] 或者 j - i == Columnindex[i] - Columnindex[j]。

int ColumnIndex[8] = { 0,1,2,3,4,5,6,7 }; // 第i个数字表示第i行皇后的列号
int count = 0;
bool isavailable(int *ColumnIndex) { // 判断该排列是否正确
	int i = 0; 
	int j = 0;
	for (i = 0; i < 8; i++) {
		for (j = 0; j < 8; j++) {
			if (j != i) {
				if ((i - j == ColumnIndex[i] - ColumnIndex[j]) || (i - j == ColumnIndex[j] - ColumnIndex[i])) {
					return false; // 正反对角线
				}
			}
		}
	}
	return true;
}
void swap(int *ColumnIndex1, int *ColumnIndex2) {
	int tmp = *ColumnIndex1;
	*ColumnIndex1 = *ColumnIndex2;
	*ColumnIndex2 = tmp;
}
void printQueue(int *ColumnIndex) {
	int i = 0;
	for (i = 0; i < 8; i++) {
		printf("%d ", ColumnIndex[i]);
	}
	printf("\n");
}

void eightQueue(int *ColumnIndex, int nextQueue) {
	if (nextQueue == 8) { //递归退出条件
		if (true == isavailable(ColumnIndex)) {
			printQueue(ColumnIndex);
			count++;
		}
		return;
	}

	int i = 0;
	for (i = nextQueue; i < 8; i++) {
		swap(&ColumnIndex[nextQueue], &ColumnIndex[i]);
		eightQueue(ColumnIndex, nextQueue + 1);
		swap(&ColumnIndex[nextQueue], &ColumnIndex[i]);
	}
}

int main() {
	eightQueue(ColumnIndex, 0);
	printf("count is %d\n", count);
	//stop;
	return 0;
}

贴个其他博主四种详细解法的链接:https://blog.csdn.net/codes_first/article/details/78474226

猜你喜欢

转载自blog.csdn.net/qq_34595352/article/details/87856571