HDU 1195 Open the Lock BFS

本文通过一个具体的实例展示了如何使用BFS(宽度优先搜索)算法解决特定类型的问题。该算法被用于寻找从一种状态转换到另一种状态所需的最小步骤数,涉及状态表示、队列操作以及状态更新等关键环节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单BFS? 感觉不是很好写,不过我觉得我这种写法还是比较飘逸的。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <cstdlib>
#include <climits>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <stack>
#include <sstream>
#include <numeric>
#include <fstream>
#include <functional>

using namespace std;

#define MP make_pair
#define PB push_back
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef pair<int,int> pii;
const int INF = INT_MAX / 3;
const double eps = 1e-8;
const LL LINF = 1e17;
const double DINF = 1e60;
const int maxn = 10;
int d[maxn][maxn][maxn][maxn];

struct Node {
    int v[4],dist;
    Node(int a[4],int dd):dist(dd) {
        for(int i = 0;i < 4;i++) v[i] = a[i];
    }
};

bool insert(Node &node,int val) {
    int &vv = d[node.v[0]][node.v[1]][node.v[2]][node.v[3]];
    if(vv <= val) return false;
    vv = val;
    return true;
}

Node opr(Node node,int pos,int val) {
    node.v[pos] += val;
    if(node.v[pos] == 0) node.v[pos] = 9;
    if(node.v[pos] == 10) node.v[pos] = 1;
    return node;
}

void bfs(int a[4],int b[4]) {
    memset(d,0x7f,sizeof(d));
    queue<Node> q;
    q.push(Node(a,0));
    while(!q.empty()) {
        Node now = q.front(); q.pop();
        for(int i = 0;i < 4;i++) {
            for(int j = -1;j <= 1;j += 2) {
                Node nn = opr(now,i,j);
                if(insert(nn,now.dist + 1)) {
                    q.push(Node(nn.v,now.dist + 1));
                }
                if(i + j < 0 || i + j >= 4) continue;
                Node nn1 = now;
                swap(nn1.v[i],nn1.v[i + j]);
                if(insert(nn1,now.dist + 1)) {
                    q.push(Node(nn1.v,now.dist + 1));
                }
            }
        }
    }
}

int main() {
    int T; scanf("%d",&T);
    while(T--) {
        int tv[2][4];
        for(int i = 0;i < 2;i++) {
            for(int j = 0;j < 4;j++) scanf("%1d",&tv[i][j]);
        }
        bfs(tv[0],tv[1]);
        printf("%d\n",d[tv[1][0]][tv[1][1]][tv[1][2]][tv[1][3]]);
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/rolight/p/3939230.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值