![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> bool col[15]; bool dia1[25], dia2[25]; //dia1用来标记满足x + y = i + j的坐标, dia2用了标记满足x - y = i - j的坐标 int ans, n, f[11]; void dfs(int row, int tot) //遍历到row行,一共tot行 { if(row > tot) //找到一个合法方案 { ans++; return; } for(int i = 1; i <= tot; i++) //枚举row行的所有位置 { if(col[i] || dia1[row + i] || dia2[row - i + tot]) continue; //如果该位置可以被攻击 col[i] = dia1[row + i] = dia2[row - i + tot] = true; //将皇后放在(row, i)位置并且将可以攻击到的位置都标记 dfs(row + 1, tot); col[i] = dia1[row + i] = dia2[row - i + tot] = false; //将皇后从(row, i)取走并且这些位置标记为可以放皇后 } } void init() //在线打表:提前算出所有答案 { for(int i = 1; i <= 10; i++) { ans = 0; dfs(1, i); f[i] = ans; } } int main() { init(); while(scanf("%d", &n) != EOF && n != 0) printf("%d\n", f[n]); return 0; }
离线打表:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> int main() { int ans[11] = {0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724}, n; while(scanf("%d", &n) != EOF && n != 0) printf("%d\n", ans[n]); return 0; }