【图论】CF——B. Chamber of Secrets (0-1BFS)

链接:https://codeforces.com/problemset/problem/173/B

题目:

思路:

初识01BFS

什么是 01 BFS 呢?通常的 BFS 为一步权值为 1,而某些题需要的不是走到步数,而是某种操作数,如花费一个操作可以走 k 步,而不花费只能走 1 步,通常我们使用双端队列可插队的性质来进行代码的编写,具体的对于不花费,那么就插入到前面,而对于花费则插入到最后

本题中操作为 "四射",所以按照上面描述很快能写出来代码

代码:

cpp 复制代码
#include <iostream>
#include <algorithm>
#include<cstring>
#include<cctype>
#include<string>
#include <set>
#include <vector>
#include <cmath>
#include <queue>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <memory>
#include <complex>
using namespace std;
#define int long long
#define yes cout << "Yes\n"
#define no cout << "No\n"
pair<int, int> dir[4] = { {-1,0},{0,1},{1,0},{0,-1} };
int use[1005][1005];
int dis[1005][1005][4];
deque<int> q;

void af(int x,int y,int d,int ans)
{
    if (ans < dis[y][x][d])
    {
        dis[y][x][d] = ans;
        q.push_front(d);
        q.push_front(y);
        q.push_front(x);
    }
}
void ab(int x, int y, int d, int ans)
{
    if (ans < dis[y][x][d])
    {
        dis[y][x][d] = ans;
        q.push_back(x);
        q.push_back(y);
        q.push_back(d);
    }
}
void solve()
{
    int n, m;
    cin >> n >> m;
    vector<string> mp(n);
    for (int i = 0; i < n; i++)
    {
        cin >> mp[i];
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            for (int k = 0; k < 4; k++)
            {
                dis[i][j][k] = 1e18;
            }
        }
    }
    af(m - 1, n - 1, 0, 0);
    while (!q.empty())
    {
        int x = q[0];
        int y = q[1];
        int d = q[2];
        q.pop_front();
        q.pop_front();
        q.pop_front();
        int ans = dis[y][x][d];
        int nx = x + dir[d].first;
        int ny = y + dir[d].second;
        if (nx >= 0 && nx < m && ny >=0 && ny < n)
        {
            af(nx, ny, d, ans);
        }
        if (mp[y][x] == '#')
        {
            for (int i = 0; i < 4; i++)
            {
                if (i != d)
                    ab(x, y, i, ans + 1);
            }
        }
    }
    if (dis[0][0][0] != 1e18)
        cout << dis[0][0][0] << endl;
    else
        cout << "-1\n";
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    while (t--)
    {
        solve();
    }
    return 0;
}
相关推荐
MartinYeung54 小时前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
Tian_Hang4 小时前
C++原型模式(Protype)
开发语言·c++·算法
bIo7lyA8v4 小时前
算法复杂度的渐进分析与实际运行时间的差异的技术8
算法
yuan199975 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab
汉克老师6 小时前
GESP7级C++考试语法知识(二、指数函数(3、综合练习)
c++·算法·数学建模·指数函数·gesp7级·复利
林间码客6 小时前
04 ROC曲线与AUC:从零开始手动计算
大数据·人工智能·算法
Irissgwe7 小时前
map/set/multimap/multiset 的底层逻辑与实现
数据结构·c++·算法·二叉树·stl·c·红黑树
IronMurphy7 小时前
【算法五十八】23. 合并 K 个升序链表
数据结构·算法·链表
思茂信息7 小时前
CST软件基于液态金属开关的方向图可重构天线
服务器·算法·重构·cst·仿真软件·电磁仿真
月疯7 小时前
PPG研究中暑的算法记录
算法