Leetcode 原题.
这里 N 最大会取到 13, TLE 了
代码
#include#include using namespace std;bool chess[15][15];int n;int cnt;void dfs(int depth) { if(depth == n) { cnt ++; return; } for(int i = 0; i < n; i ++) { bool qualify = true; for(int j = depth-1; j >= 0; j --) { if(chess[j][i]) { qualify = false; break; } } if(!qualify) continue; for(int k = 1; depth-k >= 0 && i-k >= 0; k++) { if(chess[depth-k][i-k]) { qualify = false; break; } } if(!qualify) continue; for(int k = 1; depth-k >= 0 && i+k < n; k ++) { if(chess[depth-k][i+k]) { qualify = false; break; } } if(!qualify) { continue; } // qualified chess[depth][i] = true; dfs(depth + 1); chess[depth][i] = false; }}int main() { while(scanf("%d", &n) != EOF) { cnt = 0; dfs(0); cout << cnt << endl; } return 0;}