洛谷P2324 [SCOI2005]骑士精神

题目链接:

kmakma!

题目分析:

启发式搜索入门经典题

  • 迭代加深:
    本题最大次数15次,超过15次直接return
  • 估价函数:
    当前走的次数和与答案的偏差值,超过16直接return

代码:

#include <bits/stdc++.h>
using namespace std;
inline int read() {
    int cnt = 0, f = 1; char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -f; c = getchar();}
    while (isdigit(c)) {cnt = (cnt << 3) + (cnt << 1) + c - '0'; c = getchar();}
    return cnt * f;
}
const char check[10][10] = 
{{'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[10] = {1, -1, 1, -1, 2, -2, 2, -2};
const int dy[10] = {2, -2, -2, 2, 1, -1, -1, 1};
char mapp[10][10];
int T, ans;
int spacex, spacey;
int test() {
    int tot = 0;
    for (register int i = 0; i < 5; i++)
        for (register int j = 0; j < 5; j++)
            if (mapp[i][j] != check[i][j]) ++tot;
//  cout<<tot<<endl;
    return tot;
}
void dfs_(int cnt, int x, int y, int lastx, int lasty) {
//  cout<<x<<" "<<y<<endl;
    if (cnt + test() > 16) return;
    if (cnt >= ans) return;
    if (!test()) {ans = min(ans, cnt); return;}
    for (register int i = 0; i <= 7; ++i) {
            if (x + dx[i] < 0 || x + dx[i] > 4) continue;
            if (y + dy[i] < 0 || y + dy[i] > 4) continue;
            if (x + dx[i] == lastx && y + dy[i] == lasty) continue;
                swap(mapp[x + dx[i]][y + dy[i]], mapp[x][y]);
                dfs_(cnt + 1, x + dx[i], y + dy[i], x, y);
                swap(mapp[x + dx[i]][y + dy[i]], mapp[x][y]);
    }
}
int main() {
    T = read();
    while (T--) {
        ans = 10000;
        memset(mapp, 0, sizeof(mapp));
        for (register int i = 0; i < 5; ++i) scanf("%s", mapp[i]);
        for (register int i = 0; i < 5; ++i)
            for (register int j = 0; j < 5; ++j)
                if (mapp[i][j] == '*') spacex = i, spacey = j;
        dfs_(0, spacex, spacey, -1, -1);
        ans == 10000 ? printf("-1\n") : printf("%d\n", ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/kma093/p/11319312.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值