oral_quiz->#皇后问题#

#include <stdio.h>
#include <exception>

void Swap(int* p1, int* p2) {
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}
void Permutation(int* ColumnIndex, int start);
void ChessQueen() {
	//initial ColumnIndex
	int* ColumnIndex = new int[8];
	for(int i=0; i<8; ++i) {
		ColumnIndex[i] = i;
	}

	Permutation(ColumnIndex, 0);
}

void Permutation(int* ColumnIndex, int start) {
	if(start == 8) {
		bool bPossible = true;
		for(int i=0; i<8; ++i) {
			for(int j=i+1; j<8; ++j) {
				if(i-j == ColumnIndex[i]-ColumnIndex[j] || j-i == ColumnIndex[i]-ColumnIndex[j]) {
					bPossible = false;
					break;
				}
			}
			if(!bPossible)
				break;
		}
		if(bPossible) {
			for(int i=0; i<8; ++i)
				printf("%d ", ColumnIndex[i]);
			printf("\n");
		}
	}
	else {
		for(int i=start; i<8; ++i) {
			Swap(&ColumnIndex[i], &ColumnIndex[start]);
			Permutation(ColumnIndex, start+1);
			Swap(&ColumnIndex[i], &ColumnIndex[start]);
		}
	}
}

int main(int argc, char* argv[]) {
	ChessQueen();

	return 0;
}



你可能感兴趣的:(chess,Queen)