题目就不用描述了吧。今晚看了位操作,matrix67写的专辑 http://www.matrix67.com/blog/archives/122 里提到这个题。(今天讲搜索的时候也提到这个题 = =)
就按这个方法写了一下,其实就是dfs,思路一致,转移很直观 shr(>>) shl(<<),更新每行禁点。
速度相当快。而且很方便改成n皇后求解。
//8皇后 //92 //TIME = 0.0010s #include<cstdio> #include<cstring> #include<iostream> #include<ctime> using namespace std; #define LOWBIT(x) x&(-x) /* int t2t(int x) { int ans=0; for(int i=0; i<8; i++) { if((x&(1<<7))>>7) ans = ans*10+1; else ans*=10; x<<=1; } return ans; } */ int sum; void solve(int c, int lc, int rc) { if(c == 0xFF) { sum++; return; } // int pos = (c | lc | rc)^0xFF; //可放 //①错误,因为lc可能会超出0xFF,导致pos也超出,导致死循环 int pos = ((c | lc | rc)&0xFF)^0xFF; //可放 或 0xFF&~(c|lc|rc) while(pos) { int p = LOWBIT(pos); /* DEBUG printf("c=\t%08d\n", t2t(c)); printf("lc=\t%08d\n", t2t(lc)); printf("rc=\t%08d\n", t2t(rc)); printf("总的=\t%08d\n", t2t((c | lc | rc)^0xFF)); printf("当前p=\t%08d\n", t2t(p)); printf("可放=\t%08d\n", t2t(pos&(~p))); */ solve(c|p, (lc|p)<<1, (rc|p)>>1); pos = pos&(~p); //除掉可放 pos-=p; } } // 把0xFF 改成 (1<<n)-1 可解n皇后 int main() { sum=0; solve(0, 0, 0); printf("%d\n", sum); printf("TIME = %.4lfs", (double)clock()/CLOCKS_PER_SEC); }