HDU-1401-题解-搜索、双向bfs

本文介绍了HDU 1401 Solitaire问题的解决方案,使用双向BFS搜索策略,通过将棋子坐标转化为8位数作为状态标记,解决了在4步内判断两个状态是否可达的问题。
摘要由CSDN通过智能技术生成

HDU 1401 题解

Solitaire

题目大意

每个棋子可以跳向上下左右四个方向的格子
如果格子上有棋子,可以跳过该棋子(最多跳一个)
并且保证不跳出边界
给出两个状态,每个状态包含四个棋子的坐标
问4步之内能否从第一个状态到达第二一个状态

Time: 1000 ms
Memory: 32768 kB

解题思路及分析

对每个棋子四个方向进行bfs
由于过程是可逆的,故可以进行双向搜索
访问标记每个状态时,可以把状态的4个坐标转成一个8位数来标记
原来unordered_map自定义键值类型需要自己写哈希函数……算了,转8位数标记一样的

AC代码

//#include <bits/stdc++.h>
#include <cstdio>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <cstring>
using namespace std;

struct Pos
{
   
    int x, y;
};

struct State
{
   
    Pos pos[4];
    int step;
};

bool cmp(Pos a, Pos b)
{
   
    return (a.x == b.x) ? (a.y < b.y) : (a.x < b.x);
}

// unordered_map<State, bool> vis1, vis2;
unordered_map<int, bool> vis1, vis2;
int mp[10][10];
int dx[] = {
    1, 0, -1, 0 };
int dy[] = {
    0, 1, 0, -1 };
bool ans;

bool judge(int x, int y)    // 判断是否在边界内
{
   
    return (1 <= x && x <= 8 && 1 <= y && y <= 8);
}

int to_num(State now)   // 转成8位数
{
   
    int res = 0;
    for (int i = 0; i < 4; i++)
    {
   
        res = res * 100 + now.pos[i].x * 10 + now.pos[i].y;
    }
    return res;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值