【搜索】【模板】IDA*

· · 个人记录

IDDFS

IDDFS 就是在 dfs 的基础上,融合一点 bfs 的思想,使 dfs 的深度不超过一个 \text{maxdepth},即对搜索深度进行一定的限制,如果在该深度下没有找到答案,就继续扩大深度限制,然后继续跑 dfs,直到找到答案,具体可见我的博客。

IDA*

IDA* 是 IDDFS 的升级版本,

IDA* 实际上就是在 IDDFS 的基础上加入估价函数,以及在一些特定情况下进行剪枝。

估价函数 f 可以简单理解为在当前状态下,用最乐观的方式到终点状态的需要的步骤 h(即没有任何阻碍的情况下)加上原来已经走的步骤 g,即 f = g + h。

如果当前状态在当前深度限制下使用最乐观的方式都到不了终点状态,就可以停止递归了,因为无意义。

例题:P1379 八数码难题

思路

这个题目可以直接暴力 bfs 就过了,但是我们考虑使用 IDA*。

我们主要想一想怎么写 h() 函数,在此题中就是每个点到终点状态时该点的曼哈顿距离之和。这是最乐观的走法了,如果这样还不能满足要求,就不必继续枚举了。

代码

#include <bits/stdc++.h>

using namespace std;

const int N = 9;

int n, depth;
vector<int> state(N), des = {1, 2, 3, 8, 0, 4, 7, 6, 5};
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int x[N], y[N];

int h() {           // 估价函数
    int dis = 0;
    for (int i = 0; i < 9; i++) {
        int k = state[i];
        if (state[i]) {
            dis += abs(i / 3 - x[k] / 3) + abs(i % 3 - y[k] % 3);
        }
    }
    return dis;
}

bool dfs(int space, int dep) {
    if (dep > depth) return false;// 超过深度限制
    if (state == des) return true;// 找到目标
    if (dep + h() > depth) return false;// 根本到不了

    int sp = -1;                // 找到空格
    for (int i = 0; i < 9; i++)
        if (!state[i])
            sp = i;

    int cx = sp / 3, cy = sp % 3;

    vector<vector<int> > tmp(3, vector<int>(3));
    for (int i = 0; i < 9; i++) tmp[i / 3][i % 3] = state[i];

    for (int i = 0; i < 4; i++) {
        int nx = cx + dx[i], ny = cy + dy[i];
        if (nx < 0 || ny < 0 || nx > 2 || ny > 2) continue;
        if (nx == space / 3 && ny == space % 3) continue;// 不走回头路。
        swap(state[cx * 3 + cy], state[nx * 3 + ny]);// 移动
        if (dfs(sp, dep + 1)) return true;
        swap(state[cx * 3 + cy], state[nx * 3 + ny]);
    }
    return false;
}

int main() {
    for (int i = 0; i < N; i++) x[des[i]] = i, y[des[i]] = i;
    for (int i = 0; i < N; i++) scanf("%1d", &state[i]);
    for (depth = 0; ; depth++) {
        if (dfs(-1, 0)) {
            cout << depth << '\n';
            return 0;
        }
    }
    return 0;
}

练习

MyBlog: POJ3134. Power Calculus 题解

MyBlog: UVA 1343 旋转游戏题解

MyBlog: P2346 四子连棋题解

MyBlog: P2324 [SCOI2005] 骑士精神题解

MyBlog: UVA529 Addition Chains 题解