#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;
}