简单弄了个八皇后来玩玩~
弄了个八皇后,细节方面弄了很久,看看效果如何~程序代码:
#include<stdio.h> #include<string.h> void fun ( void ); unsigned check(const unsigned short [],unsigned,unsigned ); void set( unsigned short [],unsigned*,unsigned,unsigned ); void print( unsigned,unsigned ); int main( void ) { fun(); return 0; } void fun ( void ) { #define _NUM(x,s) (((x)>>(3*(s)))&7) unsigned short s[3]; unsigned i=0; unsigned j=0; unsigned x=0; unsigned count=0; memset(s,0,sizeof (s)); while (1) { for (;j!=8;++j) { if (!check(s,i,j)) continue; set(s,&x,i++,j); break; } if (!i) break; else if (i==8) print(x,++count); else if (j!=8) { j=0; continue; } --i; j=_NUM(x,i); set(s,&x,i,j++); } printf("八皇后问题共有%u种情况!\n",count); #undef _NUM } unsigned check(const unsigned short s[],unsigned i,unsigned j ) { if (s[0]&(1<<j)) return 0; if (s[0]&(1<<8+i)) return 0; if (s[1]&(1<<8+j-i)) return 0; if (s[2]&(1<<15-j-i)) return 0; return 1; } void set( unsigned short s[],unsigned* x,unsigned i,unsigned j) { s[0]^=1<<j; s[0]^=1<<8+i; s[1]^=1<<8+j-i; s[2]^=1<<15-j-i; *x^=j<<3*i; } void print( unsigned x ,unsigned count ) { #define _NUM(x,s) (((x)>>(3*(s)))&7) unsigned i; printf("第%u种情况如下:\n\n",count); for (i=0;i!=8;++i) { unsigned j; for (j=0;j!=8;++j) putchar(j==_NUM(x,i)?'o':'*'); puts(""); } puts(""); #undef _NUM }
[此贴子已经被作者于2018-3-9 20:32编辑过]