1.自然语言描述
迭代加深搜索是在原本的深度优先搜索基础上,控制了遍历状态空间树的深度;比如:第一次DFS,控制深度为depth,看在这种情况下是否能搜索到答案状态,如果没搜到,第二次DFS控制深度为depth+1,在看是否能搜到答案状态……以此类推,通过不断加大深度来搜索答案状态;迭代加深搜索适合于答案位于状态空间树的较浅层次但是整个状态空间树的深度非常大(直接搜索整个状态空间树会非常耗时/爆栈)
同时,对于优先遍历的分支的选择,也有较优的方法:即优先遍历深度较小的树枝;这样有更大的概率能先搜到答案状态。
2.代码描述
题目:Acwing.170 加成序列 题目链接
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=110;
int x[MAXN];
int n,cnt;
bool dfs(int u,int depth)
{
if(u>depth) return false;//超过深度限制,则说明这一条路上没有答案结点
if(x[u-1]==n) return true;//找到答案结点
bool st[MAXN];
memset(st,false,sizeof(st));//避免x[i]+x[j]的值重复计入
for(int i=u-1;i>=0;i--){
//优先深度较小的树枝:从较大数开始选
for(int j=i;j>=0;j--){
int s=x[i]+x[j];
if(st[s]||s<=x[u-1]||s>n) continue;
st[s]=true;
x[u]=s;
if(dfs(u+1,depth))
return true;
}
}
return false;
}
int main(void)
{
x[0]=1;//序列第一个元素恒为1
while(cin>>n&&n){
int depth=1;//每次DFS都加大深度,直到搜索到答案结点
while(!dfs(1,depth)) depth++;
for(int i=0;i<depth;i++)
cout<<x[i]<<' ';
cout<<endl;
}
return 0;
}