/*
2008.7.7 g++ 通过测试
*/
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define ROWS 8
//代表8个皇后的位置
int queens[ROWS];
//递归算法,在某一行放入皇后
void fill(int);
//检测该位置是否符合要求
int checked(int, int);
void show_queens();
int main() {
fill(0);
return 0;
}
void fill(int rowindex) {
for(int i=0; i if(checked(rowindex, i) == 1) {
queens[rowindex] = i;
if(rowindex == ROWS-1) {
show_queens();
} else {
fill(rowindex + 1);
}
} else {
continue;
}
}
}
int checked(int rowindex, int value) {
// printf("check %d %d\n", rowindex, value);
if(rowindex == 0)return 1;
for(int i=0; i if(value == queens[i]) {
// printf("--------------------------------\n");
return 0;
}
}
int tmpindex = rowindex;
int tmp1,tmp2;
tmp1 = tmp2 = value;
while((--tmpindex) >= 0) {
if((tmpindex >= 0 && tmpindex < ROWS) && (queens[tmpindex] == --tmp1 || queens[tmpindex] == ++tmp2)) {
// printf("++++++++++++++++++++++++++++++++++\n");
return 0;
}
}
return 1;
}
void show_queens() {
printf("queens:");
for(int i=0; i printf("%d\t", queens[i]);
}
printf("\n");
}
阅读(1292) | 评论(0) | 转发(0) |