【图论】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;
}
相关推荐
Q741_14741 分钟前
C++ 前缀和 高频笔试考点 实用技巧 牛客 DP34 [模板] 前缀和 题解 每日一题
开发语言·c++·算法·前缀和·牛客网
RTC老炮2 小时前
webrtc弱网-LossBasedBandwidthEstimation类源码分析与算法原理
网络·算法·webrtc
豆浩宇2 小时前
Conda环境隔离和PyCharm配置,完美同时运行PaddlePaddle和PyTorch
人工智能·pytorch·算法·计算机视觉·pycharm·conda·paddlepaddle
一只鱼^_2 小时前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
小刘的AI小站3 小时前
leetcode hot100 二叉搜索树
算法·leetcode
自信的小螺丝钉3 小时前
Leetcode 876. 链表的中间结点 快慢指针
算法·leetcode·链表·指针
红豆怪怪3 小时前
[LeetCode 热题 100] 32. 最长有效括号
数据结构·python·算法·leetcode·动态规划·代理模式
愚润求学3 小时前
【贪心算法】day6
c++·算法·leetcode·贪心算法
AI 嗯啦3 小时前
计算机的排序方法
数据结构·算法·排序算法
l12345sy4 小时前
Day23_【机器学习—聚类算法—K-Means聚类 及评估指标SSE、SC、CH】
算法·机器学习·kmeans·聚类·sse·sc·ch