经典深度搜索
水题
代码思路
n个位置上进行全排列,深度搜索以每个位置为深度(标识)
**深度边界 **:当深度大于 n 位置
搜索内容 :
- 用for循环固定每个位置上的数字
- 判断当前数字是否出现在前面的位置:如果出现则跳过,如果没出现,则标记为出现,记录当前数字,搜索下一个位置,搜索结束后,将该数字记为未出现。
代码实现
#include<bits/stdc++.h>
int n;
int used[15],a[15];
void print() {// 打印函数
for(int i = 1; i <= n; ++i){
printf("%.5d",a[i]);
}
puts(" ");
return;
}
void dfs(int depth){
if(depth > n) return;
for(int i= 1; i <= n; ++i){
if(!used[i]){
used[i] = 1;
a[[depth] = i;
dfs(depth + 1);
used[i] = 0;
}
}
return
}
int main() {
cin >> n;
dfs(1);
return 0;
}