数据结构之八皇后问题

来源:互联网 发布:淘宝怎么兼职 编辑:程序博客网 时间:2024/06/04 08:14

用栈实现的八皇后问题

代码如下:

#include "stdio.h"#include "stdlib.h"#include "math.h"#define _size 100 //栈的大小#define len 8/** 八皇后问题* 对于两点(x1,y1),(x2,y2)* 不能同行 x1 != x2* 不能同列 y1 != y2* 不能在对角线上 斜率的绝对值 |k| != 1 |x1 - x2| != |y1 - y2| */typedef struct{int x;int y;}*point,_point;typedef struct{point *base;point *top;int size;}*stack,_stack;int place(_stack st,int x,int y);void InitStack(stack *S);void push(stack st,point p);point pop(stack st);int length(stack st);int isEmpty(stack st);point getPoint(int i,int j);void InitStack(stack *S){(*S) = (stack)malloc(sizeof(_stack));                           (*S)->base = (point*) malloc ( _size*sizeof(_point) );(*S)->top = (*S)->base;(*S)->size = _size;}void push(stack st,point p){st->top++;*st->top = p;}point pop(stack st){point p = *st->top;st->top--;return p;}int length(stack st){return st->top - st->base;}int isEmpty(stack st){if(length(st) == 0)return 1;return 0;}point getPoint(int i,int j){point p = (point)malloc(sizeof(_point));p->x = i;p->y = j;return p;}int place(_stack s,int x,int y){stack st = &s;point p;while(!isEmpty(st)){p = pop(st);if(p->x == x || p->y == y || abs(x - p->x) == abs(y - p->y) )return 0;}return 1;}int main(){int i,j;stack st;point p;InitStack(&st);push(st,getPoint(0,0));i=1,j=0;do{for(;i<len;i++){for(;j<len;j++)if(place(*st,i,j)){push(st,getPoint(i,j));if(length(st) == len)goto endF;}j = 0;}p = pop(st);i = p->x;j = p->y + 1;}while(!isEmpty(st));endF:while(!isEmpty(st)){p = pop(st);printf("(%d,%d) => ",p->x + 1,p->y + 1);}printf("\n");}

0 0