关于八皇后的非递归解决

趁着项目交付测试的空闲,找了这个很久之前就比较感兴趣的问题来写,总体看来效果不错,求得了全部92个解,话不多说,直接上代码了。

#include <stdio.h>

//建立保存皇后位置的栈
typedef struct stack 
{
	int line[8];
	int colum[8];
	int top;
	int size;
}STACK;

//实现栈的基本方法
STACK* init(STACK * stack,int size)
{
	int i = 0;

	if(stack == NULL)
	{
		stack = (STACK *)malloc(sizeof(STACK));
	}

	for(i = 0;i < size;++i)
	{
		stack->line[i] = 0;
		stack->colum[i] = 0;
	}
	stack->top = -1;
	stack->size = size;
	return stack;
}

int pop(STACK * stack)
{
	if(stack == NULL)
	{
		printf("Stack is not init,can not pop\n");
		return -1;
	}
	if(stack->top == -1)
	{
		printf("Stack is empty,can not pop\n");
		return -1;
		
	}
	stack->line[stack->top] = 0;
	stack->colum[stack->top] = 0;
	stack->top -= 1;
	return stack->top;
}

int push(STACK * stack,int line,int colum)
{
	if(stack == NULL)
	{
		printf("Stack is not init,can not push\n");
		return -1;
	}
	if(stack->top == (stack->size - 1))
	{
		printf("Stack is full,can not push\n");
		return -1;
	}
	stack->top += 1;
	stack->line[stack->top] = line;
	stack->colum[stack->top] = colum;
	return stack->top;
}

int judge(STACK * stack,int line,int colum)
{
	int i = 0;
	if(stack == NULL)
	{
		printf("Stack is null,can not judege the legitimacy\n");
		return -1;
	}
	for(i = 0;i <= stack->top;++i)
	{
		int dl = line - stack->line[i];
		int dc = colum - stack->colum[i];
		if(dl == 0 || dc == 0 )
		{
			return -1;
		}
		if( dl == dc || dl == -dc)
		{
			return -1;
		}
	}
	return 1;
}

//结果打印函数
int print_stack(STACK * stack,int result_count)
{
	printf("====reday to print stack %2d====\n", result_count);
	int i = 0;
	int j = 0;
	if(stack == NULL)
	{
		printf("Stack is null,can print it !\n");
		return -1;
	}

	for(i = 0; i < stack->size; ++i)
	{
		for(j = 0; j < stack->size; ++j)
		{
			if( j == (stack->colum[i] -1))
				printf("1 ");
			else 
				printf("0 ");
		}
		printf("\n");
	}
	printf("====  stack   print   end   ====\n");
}

int main(int argc, char * argv[])
{
	int i = 0;
	int j = 0;
	int startcolum = 1;
	int result_count = 0;
	STACK * stack = NULL;
	
	stack = init(stack,8);
	for(i = 1; i <= stack->size; ++i)
	{
		for(j = startcolum; j <= stack->size; ++j)
		{
			int ret = judge(stack,i,j);
			if(ret == 1)
			{
				push(stack,i,j);
				startcolum = 1;
				break;
			}
		}
		if(stack->top != (i-1) || stack->top == 7)
		{
			if(stack->top == 7)
			{
				result_count ++;
				print_stack(stack,result_count);
			}
			i = stack->line[stack->top] - 1;
			startcolum = stack->colum[stack->top] + 1;
			pop(stack);
		}
		
	}
	return 1;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值