八皇后问题

#include<stdio.h>

#include<stdlib.h>

#define EIGHT 8

#define TRUE 1

#define FALSE 0

int queen[EIGHT];

int number = 0;

int attack(int row,int col) {

 int i = 0, atk = FALSE;

 int offset_row, offset_col;

 while ((atk != TRUE)&&i<col) {

  offset_col = abs(i-col);

  offset_row = abs(queen[i] - row);

  if ((queen[i] == row)||(offset_row == offset_col)) {

   atk = TRUE;

  }

  i++;

 }

 return atk;

}

void print_table() {

 int x = 0, y = 0;

 number += 1;

 //printf("\n");

 printf("\n@@@@@@@@@@ % d\n\t",number);

 for (x=0; x < 8;x++) {

  for (y=0; y < 8; y++) {

   if (x == queen[y]) {

    printf("<q>");

   }

   else printf("<->");

  }

  printf("\n\t");

 }

}

void decide(int value) {

 int i = 0;

 while (i<EIGHT) {

  if (attack(i,value) != TRUE) {

   queen[value] = i;

   if (value == 7) {

    print_table();

   }

   else {

    decide(value+1);

   }

  }

  i++;

 }

}

int main() {

 decide(0);

 return 0;

}






//错误案例无回溯

#include<stdio.h>

#include<stdlib.h>

//#include<math.h>

#define STACK_MAX 8

#define TRUE 1

#define FALSE 0

int map[STACK_MAX][STACK_MAX] = { 0 };

typedef struct Node{

 int col;

 int row;

 struct Node *next;

}Node,*Linklist;

int total = 0;//计算有几组解

void print_table(Linklist head) {

 Linklist p = head->next;

 while (p != NULL) {

  map[p->row][p->col] = 1;

  p = p -> next;

 }

 printf("\n");

 for (int i = 0; i < STACK_MAX;i++) {

  for (int j = 0; j < STACK_MAX; j++) {

   printf("%d ",map[i][j]);

  }

  printf("\n");

 }

}

int attack(Linklist head) {

 Linklist p = head->next,q;

 q = p;

 q = q -> next;

 int offset_col,offset_row,atk=FALSE;

 while (q != NULL && atk != TRUE) {

  offset_row = abs((q->row)-(p->row));

  offset_col = abs((q->col)-(p->col));

 

  if (offset_col == offset_row ||(offset_row == 0)|| (offset_col == 0)) {

 

   atk = TRUE;

  }

  q = q->next;

 }

 return atk;

}

void decide_position(int col) {

 Linklist node1 = (Linklist)malloc(sizeof(Node));

 node1->col = 0;

 node1->row = 0;

 node1->next = NULL;

 Linklist node = (Linklist)malloc(sizeof(Node));

 node->next = node1;

step:

 int i = 0;

 Linklist head;

 while (i < STACK_MAX) {

  head = (Linklist)malloc(sizeof(Node));

  node->row = i;

  node->col = col;

  head->next = node;

  if (attack(head) != TRUE) {

 

   printf("%d %d \n",i,col);

   if (col == 7) {

    print_table(head);

    break;

   }

   else {

    col++;

    node = head;

    goto step;

   }

  }

  else {

   i++;

  }

 }

 if (col < 7) {

  col++;

  goto step;

 }

 

}

int main() {

 decide_position(0);

 return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值