【图论】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;
}
相关推荐
『昊纸』℃1 小时前
《C语言电子新-2026最新版》-编程语言与程序
数据结构·算法·程序设计·编程语言·软件开发
吃好睡好便好8 小时前
用while循环语句求和
开发语言·学习·算法·matlab·信息可视化
王璐WL8 小时前
【C语言入门级教学】函数的概念2
c语言·数据结构·算法
不知名的忻9 小时前
B 树与 B+ 树:面试完全指南
b树·算法·面试·b+树
运筹vivo@10 小时前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
索木木10 小时前
NCCL SHARP 和 TREE算法
java·服务器·算法
心中有国也有家11 小时前
hccl 架构拆解:昇腾集合通信库到底在做什么?
人工智能·经验分享·笔记·分布式·算法·架构
小O的算法实验室12 小时前
2026年MCS,Q-learning增强MOPSO与改进DWA融合算法+复杂三维地形下特定移动机器人动态路径规划
算法
Peter·Pan爱编程13 小时前
10. new_delete 不是 malloc_free 的包装
c++·人工智能·算法
故事和你9114 小时前
洛谷-【动态规划1】动态规划的引入2
开发语言·数据结构·c++·算法·动态规划·图论