搜索与图论①-深度优先搜索(DFS)

深度优先搜索(DFS)

例题一(指数型枚举)

把 1∼n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。

输入格式
一个整数 n。

输出格式
按照从小到大的顺序输出所有方案,每行 1 个。

首先,同一行相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。

数据范围
1≤n≤9
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

题解

#include<cstdio>
#include<iostream>


using namespace std;
const int N=10;
int n;
int path[N];
int used[N];
void dfs(int u){
    if(u>n){
        for(int i=1;i<=n;i++){
            cout<<path[i]<<" ";
        }
        cout<<endl;
        return;
    }
    
    for(int i=1;i<=n;i++){
        if(!used[i]){
            path[u]=i;
            used[i]=true;
            dfs(u+1);
            used[i]=false;
        }
    }
}
int main(){
    cin>>n;
    dfs(1);
    
    return 0;
}

例题二(n皇后问题)

posted @ 2022-03-30 19:52  open520  阅读(44)  评论(0)    收藏  举报