经过修改的八皇后最精简的实现,总共有92种解法,也就50行代码。
代码是简单的,少量的,但是思考的过程确实非常曲折的,繁复的,之前实现的八皇后太过低效和杂乱,主要是因为自身的思考能力还不强,这次作了彻底的修改,同时把以前实现的代码也发到了blog上,作为以后可供参考的教训。本篇是最终的最精减的代码:
/* 8 queens final version 1.9.1 chessboard:row number[1-8],column number[1-8] */ #include <stdio.h> #include <math.h> void put_queens(int chessbd[],int rnum); int test(int chessbd[],int rnum,int pos ); static int count = 0; int chessbd[9]; //if it is put in main(),then it is a local variable.[remember to initialize] void put_queens(int chessbd[],int rnum){ int i; if(rnum > 8){ //found a solution. //print the solution. //to find another solution. count++; }else{ for(i = 1;i <= 8 ; i++){ //test whether the condition is satisfied. if(test(chessbd,rnum,i) == 1){ chessbd[rnum] = i; put_queens(chessbd,rnum+1); } } } } int test(int chessbd[],int rnum,int pos ) { int ret; int i; int flg; ret = 1; for(i = 1 ; i < rnum ; i++){ //如果下一个皇后和正在考虑的前一个皇后的水平距离为0(列相同) //或者等于垂直距离(在一条对角线上),就返回 0. flg = abs(chessbd[i]- pos); if(flg == 0 || flg == rnum - i){ ret = 0; break; } } return ret; } int main(int argc,char* argv[]){ put_queens(chessbd,1); printf("\n@@:found solutions:%d item(s)\n\n",count); return 0; }