跳到正文

算法·理论

搜索进阶-迭代加深、启发式学习笔记

KelvinHappy约 31 分钟
原文
文章信息与版本

文章信息

发布
2026年3月9日
收录
2026年10月3日
更新
2026年11月5日
篇幅
约 31 分钟

版本

  1. v1当前

引入A*算法

在搜索的过程中,程序经常会“南辕北辙”,在一个完全相反的道路上走很远,耗费大量时间。这个时候,我们就可以设置一个估价函数,来估计从现在这个点到终点的一个大概距离。 我们对于节点为ii的点,一般把已经走的步数定义为g(i)g(i)函数,把预估的步数设为h(i)h(i)函数,把大概的总步数设为f(i)f(i)函数,则f(i)=g(i)+h(i)f(i) = g(i) + h(i)。程序会按照f(i)f(i)进行排序,然后先挑最优秀的进行搜索,为了更高效,排序这个步骤我们用优先队列实现。程序实现用BFS,只要把队列换成优先队列即可,无需做任何大调整。

例题1 迷宫的最短路径

这里,我们将估价函数设定为这个节点到终点的曼哈顿距离,曼哈顿距离是至从一点到另外一点在格点上行走的最短距离,用(x1−x0)+(y1−y0)(x_1 - x_0) + (y_1 - y_0)这个公式实现。
AC code:

C++
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int n,m;
const int N = 100,dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
char mymap[N + 1][N + 1],okx,oky,nowx,nowy;
bool vis[N + 1][N + 1];
int h(int x,int y){
    return abs(x - okx) + abs(y - oky);
}
struct node{
    int x,y,step;
    friend bool operator < (node a,node b){
        return a.step + h(a.x,a.y) > b.step + h(b.x,b.y);
    }
};
int main(){
    cin>>n>>m;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= m;j++){
            cin>>mymap[i][j];
            if(mymap[i][j] == 'S') nowx = i,nowy = j;
            else if(mymap[i][j] == 'G') okx = i,oky = j;
        }
    }
    priority_queue<node> q;
    q.push({nowx,nowy,0});
    while(!q.empty()){
        node tmp = q.top();
        nowx = tmp.x,nowy = tmp.y;
        q.pop();
        if(vis[nowx][nowy]) continue;
        vis[nowx][nowy] = true;
        if(nowx == okx && nowy == oky){
            cout<<tmp.step<<endl;
            return 0;
        }
        for(int i = 0;i <= 3;i++){
            int tox = nowx + dx[i],toy = nowy + dy[i];
            if(tox < 1 || tox > n || toy < 1 || toy > m)
                continue;
            if(mymap[tox][toy] == '#') continue;
            if(vis[tox][toy]) continue;
            q.push({tox,toy,tmp.step + 1});
        }
    }
    cout<<-1<<endl;
}

引入IDE算法

目前为止,我们学习了DFS和BFS,不过,他们都有一些缺点:DFS搜索深度太深,有时会“执着”地搜索一条很长很长的路径;BFS在每层数量很多的时候,会浪费大量空间。这时,我们就想出了一个办法:在DFS搜索时,设置一个阀门,搜索深度就约束在这个阀门里。 这样就能够减少DFS的搜索深度了。

例题2 埃及分数(减弱版)

我们发现,我们既不知道搜索深度(有多少个分母),又不知道搜索广度(分母最大是多少)。怎么办呢?
首先,对于搜索深度,我们就可以用上面提到的IDE算法,枚举搜索深度。
然后,对于搜索广度,我们可以数学讨论一下:
1.后面的分数必然比前面的小,也就是后面的分母必然比前面的大。 这样就可以得到xx的下界之一。
2.对于一个分数ab\displaystyle\frac{a}{b}来说,如果要减掉一个单位分数1x\displaystyle\frac{1}{x},那么原来的分数必须比单位分数大,也就是ab≥1x\displaystyle\frac{a}{b} \ge \frac{1}{x}。因为两个分数都是正数,所以可以同时取倒数,就得到xx的下界之一,也就是ba≤x\displaystyle\frac{b}{a} \le x。
3.当然,因为后面的都比这个分数小,所以假设后面所有的位置都填这个分数还不够,就说明这个分数太小了。 假设还剩kk个数,则ab≤kx\displaystyle\frac{a}{b} \le \frac{k}{x}。因为两个分数都是正数,所以可以同时取倒数,也就是ba≥xk\displaystyle\frac{b}{a} \ge \frac{x}{k},两边在同时乘kk,就得到b×ka≥x\displaystyle\frac{b \times k}{a} \ge {x},也就是xx的上界。
AC code:

C++
#include<iostream>
#include<cmath>
#define int long long
using namespace std;
int a,b;
bool flag = false;
const int N = 1e7;
int ans[N + 1],tmp[N + 1];
int gcd(int a,int b){
    return b == 0? a : gcd(b,a % b);
}
void mul(int a,int b,int x,int &tmpa,int &tmpb){
    tmpb = b * x;
    tmpa = a * x - b;
    int gcd1 = gcd(tmpa,tmpb);
    tmpa /= gcd1;
    tmpb /= gcd1;
}
void dfs(int step,int limit,int a,int b){
    if(step > limit){
        if(a == 0){
            flag = true;
            if(tmp[limit] < ans[limit]){
                for(int i = 1;i <= limit;i++)
                    ans[i] = tmp[i];
            }
            return ;
        }
    }
    for(int i = max(tmp[step - 1] + 1,b / a + (b % a != 0));
        i <= b * (limit - step + 1) / a;i++){
        tmp[step] = i;
        int tmpa,tmpb;
        mul(a,b,i,tmpa,tmpb);
        dfs(step + 1,limit,tmpa,tmpb);
    }
}
signed main(){
    cin>>a>>b;
    for(int i = 1;i <= N;i++) ans[i] = 4e18;
    for(int i = 1;!flag;i++){
        dfs(1,i,a,b);
        if(flag){
            for(int j = 1;j <= i;j++)
                cout<<ans[j]<<" ";
        }
    }
}

综合运用

例题3 八数码

这题很明显会用到A*算法去做。而估价函数我们就可以设计为当前状态和目标有多少方块不同。
然后,就没有然后了。
AC code:

C++
#include<iostream>
#include<map>
#include<queue>
using namespace std;
const string goal = "123804765";
const int d[9][4] = {{-1,3,-1,1},{-1,4,0,2},{-1,5,1,-1},
{0,6,-1,4},{1,7,3,5},{2,8,4,-1},{3,-1,-1,7},{4,-1,6,8},
{5,-1,7,-1}};
map<string,bool> vis;
int h(string a){
    int cnt = 0;
    for(int i = 0;i <= 8;i++)
        cnt += (goal[i] != a[i]);
    return cnt;
}
struct node{
    string s;
    int step;
    friend bool operator < (node a,node b){
        return a.step + h(a.s) > b.step + h(b.s);
    } 
};
int main(){
    string s;
    cin>>s;
    priority_queue<node> q;
    q.push({s,0});
    while(!q.empty()){
        node tmp = q.top();
        string now = tmp.s;
        q.pop();
        vis[now] = true;
        if(now == goal){
            cout<<tmp.step<<endl;
            return 0;
        }
        int zero = -1;
        for(int i = 0;i <= 8;i++)
            if(now[i] == '0')
                zero = i;
        for(int i = 0;i <= 3;i++){
            if(d[zero][i] == -1) continue;
            string to = now;
            swap(to[zero],to[d[zero][i]]);
            if(vis[to]) continue;
            q.push({to,tmp.step + 1});
        }
    }
    cout<<0<<endl;
}

例题4 采药

虽然本题是DP模板题,但是需要用搜索做。
那么在这里,应该用哪种搜索呢?答案是:用可行性剪枝+A*算法。 这里我们将估价函数(即h(i)h(i))的意义改一下,变成可行性的判断。具体而言,就是将估价函数作为一个乐观的估计,如果这个乐观的估计加上当前的收益依然不够最大值,则进行剪枝。
首先,我们尝试将性价比作为当前的指标(当然,性价比只是做一个估计,并非真正的答案)并排序,然后我们这样设计估价函数:按性价比从大到小的顺序计算,然后一个一个累加,如果不够整块拿一部分。最终得到一个答案。这其实就相当于做了一个部分背包。
这就是A*算法的第二种妙用。
AC code:

C++
#include<iostream>
#include<algorithm>
using namespace std;
int m;
struct node{
    int time,c;
};
const int N = 100;
node a[N + 1];
bool cmp(node a,node b){
    return a.c * 1.0 / a.time > b.c * 1.0 / b.time;
}
int h(int t,int step){
     int i = step,sum = 0;
     while(t > a[i].time && i <= m){
          sum += a[i].c;
          t -= a[i].time;
          i++;
     }
     if(i <= m){
          sum += (double)t / a[i].time * a[i].c;
     }
     return sum;
}
int ans = 0;
void dfs(int t,int step,int sum){
    if(step > m){
        ans = max(ans,sum);
        return ;
    }
    if(sum + h(t,step) < ans) return ;
    for(int i = step;i <= m;i++){
        if(t < a[i].time) continue;
        dfs(t - a[i].time,i + 1,sum + a[i].c);
    }
    dfs(t,m + 1,sum);
}
int main(){
    int t;
    cin>>t>>m;
    for(int i = 1;i <= m;i++) cin>>a[i].time>>a[i].c;
    sort(a + 1,a + 1 + m,cmp);
    dfs(t,1,0);
    cout<<ans<<endl;
}

例题5 骑士精神

这道题因为步数不确定,所以使用IDE算法,限制搜索深度,但是这样依然不能通过。
因此,我们需要采取上一题的用可行性剪枝+A*算法,这里的估价函数我们可以用例题3的启发函数,设计为当前状态和目标有多少方块不同。可以说,这道题采用了多种思路,是一道非常不错的综合题。
AC code:

C++
#include<iostream>
#include<map>
using namespace std;
int ans = -1;
const char goal[5][5] =
{'1','1','1','1','1',
'0','1','1','1','1',
'0','0','*','1','1',
'0','0','0','0','1',
'0','0','0','0','0'};
const int dx[8] = {-2,-2,-1,1,2,2,1,-1};
const int dy[8] = {-1,1,2,2,1,-1,-2,-2};
int h(char m[5][5]){
    int sum = 0;
    for(int i = 0;i <= 4;i++){
        for(int j = 0;j <= 4;j++){
            if(m[i][j] == '*') continue;
            if(m[i][j] != goal[i][j]) sum++;
        } 
    }
    return sum;
}
void dfs(int step,int limit,char now[5][5]){
    if(step == limit){
        for(int i = 0;i <= 4;i++)
            for(int j = 0;j <= 4;j++)
                if(now[i][j] != goal[i][j])
                    return ;
        ans = limit;
        return ;
    }
    if(step + h(now) > limit) return ;
    int starx = 0,stary = 0;
    for(int i = 0;i <= 4;i++)
        for(int j = 0;j <= 4;j++)
            if(now[i][j] == '*')
                starx = i,stary = j; 
    for(int i = 0;i < 8;i++){
        int nxtx = starx + dx[i],nxty = stary + dy[i];
        if(nxtx < 0 || nxtx > 4 || nxty < 0 || nxty > 4)
            continue;
        swap(now[starx][stary],now[nxtx][nxty]);
        dfs(step + 1,limit,now);
        swap(now[starx][stary],now[nxtx][nxty]);
    }
}
int main(){
    int t;
    cin>>t;
    while(t--){
        ans = -1;
        char mymap[5][5];
        for(int i = 0;i <= 4;i++)
            for(int j = 0;j <= 4;j++)
                cin>>mymap[i][j];
        for(int i = 1;i <= 15 && ans == -1;i++)
            dfs(0,i,mymap);
        cout<<ans<<endl;
    }
}

例题6 棋盘染色

首先,我们无法判断什么情况下距离目标最近,因此无法使用A*函数。
但是,我们可以考虑填几个方块,也就是迭代加深搜索。
当然,这样依然会超时,原因是因为每次都要从2525个格子中选11个,每次访问时间复杂度大约是O(25limit)O(25^{limit}),其中limitlimit指上限。如果我们一直是从前往后访问不回头,也就是每一种填法只用遍历2525个方格,而总共有C25limitC_{25}^{limit}种情况。再加上迭代加深的特性,这样能够优化很多。
AC code:

C++
#include<iostream>
#include<queue>
using namespace std;
const int dx[4] = {1,0,-1,0},dy[4] = {0,1,0,-1};
bool check(char m[5][5]){
    bool vis[5][5];
    int gox = -1,goy = -1;
    for(int i = 0;i <= 4;i++){
        for(int j = 0;j <= 4;j++){
            vis[i][j] = false;
            if(gox == -1 && m[i][j] == '1')
                gox = i,goy = j;
        }
    }
    if(gox == -1) return true;
    queue< pair<int,int> > q;
    q.push({gox,goy});
    vis[gox][goy] = true;
    while(!q.empty()){
        pair<int,int> tmp = q.front();
        q.pop();
        int nowx = tmp.first,nowy = tmp.second;
        for(int k = 0;k <= 3;k++){
            int tox = nowx + dx[k],toy = nowy + dy[k];
            if(tox < 0 || tox > 4 || toy < 0 || toy > 4) 
                continue;
            if(m[tox][toy] == '0') continue;
            if(vis[tox][toy]) continue;
            q.push({tox,toy});
            vis[tox][toy] = true;
        }
    }
    for(int i = 0;i <= 4;i++)
        for(int j = 0;j <= 4;j++)
            if(m[i][j] == '1' && !vis[i][j])
                return false;
    return true;
}
int ans = -1;
void dfs(int step,int limit,int x,int y,char m[5][5]){
    if(step > limit){
        if(check(m)) ans = limit;
        return ;
    }
    for(int j = y + 1;j <= 4;j++){
        if(m[x][j] == '1') continue;
        m[x][j] = '1';
        dfs(step + 1,limit,x,j,m);
        m[x][j] = '0';
    }
    for(int i = x + 1;i <= 4;i++){
        for(int j = 0;j <= 4;j++){
            if(m[i][j] == '1') continue;
            m[i][j] = '1';
            dfs(step + 1,limit,i,j,m);
            m[i][j] = '0';
        }
    }
    return ;
}
int main(){
    char m[5][5];
    for(int i = 0;i <= 4;i++)
        for(int j = 0;j <= 4;j++)
            cin>>m[i][j];
    for(int i = 0;i <= 25 && ans == -1;i++) dfs(1,i,0,0,m);
    cout<<ans<<endl;
}

例题7 小信的BFS迷宫

在这里,因为小信向周围走一格是不花精力的,所以我们可以将A*算法的估价函数设置为使用了多少次魔法,魔法少的靠前。
不过,还有更简单的实现方式,就是01BFS。我们可以设置一个双端队列,不使用魔法就往前插,使用魔法就往后插,这样就能达到A*算法同样的效果。
AC code:

C++
#include<iostream>
#include<deque>
using namespace std;
const int N = 1e3;
char my_map[N + 1][N + 1];
bool vis[N + 1][N + 1];
const int dx[4] = {1,-1,0,0},dy[4] = {0,0,1,-1};
struct node1{
     int x,y,step;
};
deque<node1> q;
int main(){
     int n,m,cx,cy,ex,ey;
     cin>>n>>m>>cx>>cy>>ex>>ey;
     for(int i = 1;i <= n;i++){
          for(int j = 1;j <= m;j++){
               cin>>my_map[i][j];
               vis[i][j] = false;
          }
     }
     q.push_front({cx,cy,0});
     while(!q.empty())
     {
          node1 now = q.front();
          q.pop_front();
          if(now.x == ex && now.y == ey) {
               cout<<now.step;
               return 0;
          }
          if(vis[now.x][now.y]) continue;
          vis[now.x][now.y] = true;
          for(int i = 0;i <= 3;i++){
               int nextx = now.x + dx[i];
               int nexty = now.y + dy[i];
               if(nextx < 1 || nextx > n || nexty < 1 || nexty > m)
                    continue;
               if(my_map[nextx][nexty] == '#') continue;
               q.push_front({nextx,nexty,now.step});
          }
          for(int i = -2;i <= 2;i++){
               for(int j = -2;j <= 2;j++){
                    int nextx = now.x + i;
                    int nexty = now.y + j;
                    if(nextx < 1 || nextx > n || nexty < 1 || nexty > m)
                         continue;
                    if(my_map[nextx][nexty] == '#') continue;
                    q.push_back({nextx,nexty,now.step + 1});
               }
          }
     }
     cout<<-1;
}

例题8 推箱子

这也是01BFS的一道题目。我们让不推箱子的优先,推箱子的排在后面就可以了。
AC code:

C++
#include <iostream>
#include <deque>
#include <cstring>
#include <climits>
using namespace std;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
struct node {
    int bx, by, px, py, s;
    node(int a, int b, int c, int d, int e) : bx(a), by(b), px(c), py(d), s(e) {}
};
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        int m, n;
        cin >> m >> n;
        int g[7][7], bx, by, px, py, tx, ty;
        memset(g, 0, sizeof(g));
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                cin >> g[i][j];
                if (g[i][j] == 2) {bx = i; by = j;}
                else if (g[i][j] == 3) {tx = i; ty = j;}
                else if (g[i][j] == 4) {px = i; py = j;}
            }
        }
        int d[7][7][7][7];
        memset(d, 0x3f, sizeof(d));
        deque<node> q;
        q.push_front(node(bx, by, px, py, 0));
        d[bx][by][px][py] = 0;
        int ans = INT_MAX;
        while (!q.empty()) {
            node cur = q.front();
            q.pop_front();
            if (cur.bx == tx && cur.by == ty) {
                ans = min(ans, cur.s);
                continue;
            }
            if (cur.s > d[cur.bx][cur.by][cur.px][cur.py]) continue;
            for (int i = 0; i < 4; i++) {
                int nx = cur.px + dx[i];
                int ny = cur.py + dy[i];
                if (nx >=0 && nx < m && ny >=0 && ny < n && g[nx][ny] != 1 
                    && (nx != cur.bx || ny != cur.by) && d[cur.bx][cur.by][nx][ny] > cur.s) {
                    d[cur.bx][cur.by][nx][ny] = cur.s;
                    q.push_front(node(cur.bx, cur.by, nx, ny, cur.s));
                }
            }
            // 推箱子
            for (int i = 0; i < 4; i++) {
                int pxn = cur.bx - dx[i];
                int pyn = cur.by - dy[i];
                int nbx = cur.bx + dx[i];
                int nby = cur.by + dy[i];
                if (pxn < 0 || pxn >= m || pyn < 0 || pyn >= n || g[pxn][pyn] == 1) continue;
                if (nbx < 0 || nbx >= m || nby < 0 || nby >= n || g[nbx][nby] == 1) continue;
                bool v[7][7] = {false};
                deque<pair<int, int>> q2;
                q2.push_back({cur.px, cur.py});
                v[cur.px][cur.py] = true;
                bool ok = false;
                while (!q2.empty() && !ok) {
                    int x = q2.front().first;
                    int y = q2.front().second;
                    q2.pop_front();
                    for (int j = 0; j < 4; j++) {
                        int xx = x + dx[j];
                        int yy = y + dy[j];
                        if (xx >=0 && xx < m && yy >=0 && yy < n && g[xx][yy] != 1 
                            && !v[xx][yy] && (xx != cur.bx || yy != cur.by)) {
                            if (xx == pxn && yy == pyn) {ok = true; break;}
                            v[xx][yy] = true;
                            q2.push_back({xx, yy});
                        }
                    }
                }
                if (ok) {
                    int ns = cur.s + 1;
                    if (ns < d[nbx][nby][cur.bx][cur.by]) {
                        d[nbx][nby][cur.bx][cur.by] = ns;
                        q.push_back(node(nbx, nby, cur.bx, cur.by, ns));
                    }
                }
            }
        }
        cout << (ans == INT_MAX ? -1 : ans) << endl; 
    }
    return 0;
}
原文