DFS

原理

原理很简单,就是搜索一条路,一路走到头;

如果不符合题意,返回上一节点;

再从上一节点找另一条子节点继续往下走;

思路

path[]

该数组用来存储方法,当到达路径底部,返回该方案;

state[]

用于标记该节点是否已经使用过;

state[i]若为1,即为已经使用过;若为0,即为未使用过;

dfs(i)

表示在path[i]处填写数字,递归时就会在下一个地方填写数字;

回溯

第 i 个位置填写某个数字的所有情况都遍历后, 第 i 个位置填写另一个数字。

例题

https://www.acwing.com/solution/content/30988/

题解

#include<bits/stdc++.h>
using namespace std;
int path[10];//保存数列;
int state[10];//标记数字是否使用过;
int n;
void dfs(int x)
{
    if(x > n)//如果数字已经填完了,输出;
    {
        for(int i = 1 ; i <= n ; i++)
        {
            cout << path[i] << " ";
        }
        cout << endl;
    }
    
    for(int i = 1 ; i <= n ; i++)
    {
        if(!state[i])//如果数字i没有被用过;
        {
            path[x] = i;//放入空位;
            state[i] = 1;//标记在该情况下已使用;
            dfs(x + 1);//迭代
            state[i] = 0;//回溯,将上一个使用过的数字取消标记
        }
    }
}
int main()
{
    cin >> n;
    dfs(1);
    
    
    return 0;
}
posted @ 2022-09-28 19:16  Zilliax  阅读(62)  评论(0)    收藏  举报