趁着项目交付测试的空闲,找了这个很久之前就比较感兴趣的问题来写,总体看来效果不错,求得了全部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;
}