2060. 奶牛选美

这篇文章介绍了如何利用BFS算法解决一个编程题目——在给定的矩阵中找到包含‘X’的连通区域,并计算每个连通区域的数量。通过DFS标记连通块,然后用队列进行广度优先搜索。
摘要由CSDN通过智能技术生成

2060. 奶牛选美 - AcWing题库

思路:只有两个连通块,先标记一个连通块。之后将这个连通块全部放入队列跑一个bfs即可。

#include <bits/stdc++.h>
using namespace std;
const int N = 121;
int fx[] = {0, 0, 1, -1};
int fy[] = {1, -1, 0, 0};
bool vis[N][N];
string ph[N];
struct no {
    int x,y,cnt;
};
int main()
{
    int n,m; cin>>n>>m;
    for(int i = 0; i < n; ++i) cin>>ph[i];
    bool ok = false;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            if(ph[i][j] == 'X') {
                auto dfs = [&](auto &&self, int x, int y) -> void {
                    vis[x][y] = 1;
                    for(int i = 0; i < 4; ++i) {
                        int xx = x + fx[i], yy = y + fy[i];
                        if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
                        if(ph[xx][yy] == '.' || vis[xx][yy]) continue;
                        self(self, xx ,yy);
                    }
                };
                dfs(dfs,i,j);
                ok = true;
                break;
            }
        }
        if(ok) break;
    }
    queue<no> q;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            if(vis[i][j]) q.push({i, j, 0});
        }
    }
    while(q.size()) {
        auto tmp = q.front(); q.pop();
        for(int i = 0; i < 4; ++i) {
            int xx = tmp.x + fx[i], yy = tmp.y + fy[i];
            if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
            if(vis[xx][yy]) continue;
            vis[xx][yy] = 1;
            if(ph[xx][yy] == 'X') {
                cout<<tmp.cnt<<endl;
                return 0;
            }
            q.push({xx, yy, tmp.cnt + 1});
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

golemon.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值