骑士精神 (HYSBZ - 1085 ,简单 A* 暴搜)

一.题目链接:

HYSBZ-1085

二.题目大意:

直接看题目,懒得解释.

三.分析:

其实就是一个简单 A* 搜索 的板子

为了方便,分析就写注释里了.

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-4
#define PI acos(-1.0)
#define ll long long int
using namespace std;

int ans;
int mp[10][10];
int s[5][5] = {
    {1, 1, 1, 1, 1},
    {0, 1, 1, 1, 1},
    {0, 0, 2, 1, 1},
    {0, 0, 0, 0, 1},
    {0, 0, 0, 0, 0},
};///在这里存目标地图
int Move[8][2] = {
    {1, 2}, {1, -2}, {-1, 2}, {-1, -2},
    {2, 1}, {2, -1}, {-2, 1}, {-2, -1}
};/// 8 个方向

int check()///计算从 现地图 转化到 目标地图 所需的最佳代价 
{
    int cnt = 0;
    for(int i = 0; i < 5; ++i)
    {
        for(int j = 0; j < 5; ++j)
        {
            if(mp[i][j] != s[i][j])
                cnt++;
        }
    }
    return cnt;
}

void A_star(int y, int x, int g, int now)///类似于 dfs
{
    if(g == now)
    {
        if(check() == 0)/// 现地图 与 目标地图 相同
            ans = now;
        return;
    }
    if(~ans)/// ans != -1.
        return;
    for(int i = 0; i < 8; ++i)
    {
        int ny = y + Move[i][0];
        int nx = x + Move[i][1];
        if(ny < 0 || ny > 4 || nx < 0 || nx > 4)
            continue;
        swap(mp[y][x], mp[ny][nx]);
        if(check() + g <= now)
            A_star(ny, nx, g + 1, now);
        swap(mp[y][x], mp[ny][nx]);
    }
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        char ch;
        int y;
        int x;
        for(int i = 0; i < 5; ++i)
        {
            getchar();
            for(int j = 0; j < 5; ++j)
            {
                scanf("%c", &ch);
                if(ch == '*')
                {
                    y = i;
                    x = j;
                    mp[i][j] = 2;
                }
                else
                    mp[i][j] = ch - '0';
            }
        }
        ans = -1;
        for(int i = 0; i < 16; ++i)///枚举所需步数
        {
            A_star(y, x, 0, i);
            if(~ans)
                break;
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值