【图论】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;
}
相关推荐
普贤莲花2 分钟前
【2026年第18周---写于20260501】---舍得
程序人生·算法·leetcode
2zcode2 分钟前
基于深度学习的口腔疾病图像识别系统(UI界面+改进算法+数据集+训练代码)
人工智能·深度学习·算法
Sarvartha11 分钟前
N 个字符串最长公共子序列(LCS)求解问题
数据结构·算法
一切皆是因缘际会12 分钟前
下一代 AI 架构:基于记忆演化与单向投影的安全智能系统
大数据·人工智能·深度学习·算法·安全·架构
falldeep18 分钟前
五分钟了解OpenClaw底层架构
人工智能·算法·机器学习·架构
m0_6294947318 分钟前
LeetCode 热题 100-----16.除了自身以外数组的乘积
数据结构·算法·leetcode
weixin_4462608524 分钟前
模型能力深度对决:GPT-4o、Claude 3.5和DeepSeek V系列模型的横向评测与未来趋势洞察
人工智能·算法·机器学习
想唱rap1 小时前
应用层协议与序列化
linux·运维·服务器·网络·数据结构·c++·算法
重生之我是Java开发战士1 小时前
【笔试强训】Week3:重排字符串,分组,DNA序列
算法
We་ct1 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划