栈的使用(2)----n皇后问题

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值