#include "stdio.h"
#include "malloc.h"
#define MAX 20
typedef int Elem;
typedef struct {
Elem *rows;//在表格中的行
int length;//表示栈中元素的数量
}Stack;
void initStack (Stack *stack) {
stack->length = 0 ;
stack->rows = (Elem*)malloc(MAX*sizeof(Elem));
}
void push (Stack *stack,Elem data) {
if (stack->length > MAX) {
return;
}
stack->rows[stack->length] = data;
stack->length++;
}
//是否为空栈
int isEmpty (Stack *stack) {
if (stack->length == 0) {
return 1;
}else {
return 0;
}
}
Elem pop (Stack *stack) {
if (isEmpty(stack)) {
return -1;
}
stack->length--;
return stack->rows[stack->length];
}
int getLength (Stack *stack) {
return stack->length;
}
Elem getTop (Stack *stack) {
if (isEmpty(stack)) {
return -1;
}
return stack->rows[stack->length - 1];
}
void clearStack (Stack *stack) {
stack->length = 0;
}
void output (Stack *stack) {
int i = 0;
if (isEmpty(stack)) {
return;
}
while (i < stack->length) {
printf("%d ",stack->rows[i]);
i++;
}
printf("\n");
}
//a和b的绝对值之差
int abs (int a,int b) {
return a > b?a-b:b-a;
}
//但位置是i的时候看看相应的结果是否是满足相应的情况的。满足的话返回的是1否则返回的是0
int isLocation (Stack *stack,int i) {
int j;
int result = 1;
if (!isEmpty(stack)) {
for (j = 0;j < stack->length-1;j++) {//和它不相邻的位置的值不再同一行就可以了
if ( i == stack->rows[j]) {
result = 0;
break;
}
}
j = getTop(stack);
if (abs(j,i) <= 1) {
result = 0;
}
}
return result;
}
//n表示是几皇后的问题了
void queue (int n) {//只找出其中的一种情况出来。
Stack stack;
int i;
int flag;
initStack(&stack);
push(&stack,1);//代表的是首先压入的是第一列的第一行了,其中数组的下表数+1是相应的列数了
i = 1;
while (getLength(&stack) < n) {//但其中的元素的个数是n的时候就是满足条件的时候了
while (i <= n) {
flag = isLocation (&stack,i);
if (flag == 0) {
i++;
}else {
push(&stack,i);
break;
}
}
if ( i > n) {
i = pop(&stack)+1;
if (isEmpty(&stack)&&i > n) {//此时的情况是到第一个列的最后一行了。退出while循环。
break;
}
}else {
i = 1;
}
}
output(&stack);
}
//输出所有的可能的情况
void queueAll (int n) {
Stack stack;
int i,flag,result;
flag = 1;
i = 1;
initStack(&stack);
push(&stack,1);
while (flag) {
while (getLength(&stack) < n) {//1
while (i <= n) {//---
result = isLocation (&stack,i);
if (result == 0) {
i++;
}else {
push(&stack,i);
i = 1;
break;
}
}//----
if (i > n) {//--
i = pop(&stack) + 1;
if (isEmpty(&stack) == 1 && i > n) {
flag = 0;
break;
}
}//--
}//1
output(&stack);
i = pop(&stack) + 1;
}
}
void main () {
queueAll(4);
return;
}
其中 4表示的是4皇后问题
输出结果是:
2 4 1 3
3 1 4 2