【图论】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;
}
相关推荐
青少儿编程课堂21 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z21 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu1 天前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥1 天前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
AAA修煤气灶刘哥1 天前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
电科_银尘1 天前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真1 天前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练
是main不是漫1 天前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法
Felven1 天前
A. Iskander and Drawings
算法
qq_348231852 天前
大模型算法: 反向传播
算法