Educational Codeforces Round 138 E Cactus Wall

Cactus Wall#

01bfs

其实按照题目的意思,就必须要有一条 # 的最短路,从最左边的一列到达最右边的一列,然后是只能是斜着走,并且要保证新添加的 # 最少,而且添加的地方,其上下左右都没有 #

带着这些约束跑一个多起点多终点的 bfs 就行,因为权值的增加只有 01,因此直接 01bfs

这里的最短路指的是:添加的 # 最少

复杂度 O(mn)

简单给一个比较容易 wa 的数据

1
8 6
#.....
.#....
..#...
......
..#...
...#..
....#.
.....#
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <deque>
#include <array>
using namespace std;
#define pii pair<int, int>
vector<string>gra;
vector<vector<pii>>vis;
int n, m;
const int xi[8] = {0, 0, 1, -1, 1, -1, 1, -1};
const int yi[8] = {1, -1, 0, 0, 1, -1, -1, 1};

bool check(int x, int y)
{
    return x >= 0 && y >= 0 && x < n && y < m;
}

bool init(int xx, int yy)
{
    int f = 1;
    for(int j=0; j<4; j++)
    {
        int x = xx + xi[j], y = yy + yi[j];
        if(!check(x, y)) continue;
        if(gra[x][y] == '#') f = 0;
    }
    return f;
}

int bfs()
{
    deque<array<int, 4>>q;
    for(int i=0; i<n; i++)
    {
        if(init(i, 0))
        {
            if(gra[i][0] == '#') q.push_front({i, 0, 0, 0});
            else q.push_back({i, 0, 0, 0});
        }
    }
    while(q.size())
    {
        auto [x, y, prex, prey] = q.front();
        q.pop_front();
        if(vis[x][y].first != -1) continue;
        vis[x][y] = {prex, prey};
        if(y == m - 1) return x;
        for(int i=4; i<8; i++)
        {
            int xx = x + xi[i], yy = y + yi[i];
            if(!check(xx, yy) || !init(xx, yy)) continue;
            if(gra[xx][yy] == '#') q.push_front({xx, yy, x, y});
            else q.push_back({xx, yy, x, y});
        }
    }
    return -1;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n >> m;
        gra.resize(n);
        vis.resize(n);
        for(int i=0; i<n; i++) cin >> gra[i];
        for(int i=0; i<n; i++)
        {
            vis[i].resize(m);
            fill(vis[i].begin(), vis[i].end(), make_pair(-1, -1));
        }
        int x = bfs();
        if(x == -1) {cout << "NO\n"; continue;}
        cout << "YES\n";
        int y = m - 1;
        while(y > 0)
        {
            gra[x][y] = '#';
            int xx = vis[x][y].first;
            int yy = vis[x][y].second;
            x = xx;
            y = yy;
        }
        gra[x][y] = '#';
        for(int i=0; i<n; i++) cout << gra[i] << "\n";
    }
    cout << endl;
    return 0;
}

posted @   dgsvygd  阅读(83)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示
主题色彩