TAG
- 芝士水题、算法 − 【搜索 − D F S 】 芝士水题、算法 - 【搜索 - DFS】 芝士水题、算法−【搜索−DFS】时间复杂度
- O ( N ! ) O(N!) O(N!)
//
#include <bits/stdc++.h>
using namespace std;
// #define int long long
const int N = 15;
const int HASH = N;
bool usedJ[N << 1], usedL[N << 1], usedR[N << 1];
int n, ans;
void dfs(int cnt) {
if (cnt > n) {
ans++;
return ;
}
for (int i = 1; i <= n; i++) {
// `cnt + i + HASH` 会溢出
if (usedJ[i] == 0 && usedL[cnt + i] == 0 && usedR[cnt - i + HASH] == 0) {
usedJ[i] = usedL[cnt + i] = usedR[cnt - i + HASH] = 1;
dfs(cnt + 1);
usedJ[i] = usedL[cnt + i] = usedR[cnt - i + HASH] = 0;
}
}
}
void solve() {
scanf("%d", &n);
dfs(1);
printf("%d\n", ans);
}
signed main() {
int t = 1;
// scanf("%d", &t);
while (t--) solve();
return 0;
}
实现细节
- `
参考示意图
-
`
参考链接
作者 | 乐意奥AI