洛谷P1141 01迷宫 bfs求最大连通块+dfs记录过程

本文介绍了一种解决洛谷P1141问题的有效算法,通过两次深度优先搜索(DFS),实现对大规模网格上的连通区域快速查询。首次DFS用于标记连通块,二次DFS记录各格子答案,大幅减少重复计算,提高处理十万次询问的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

洛谷P1141 传送门


在这里插入图片描述
在这里插入图片描述


这个题是昨天下午开始写的,昨天我一直以为是求最远路径,然后交了以后不是wa就是T,今天早上学长告诉我是求最大连通块。。。

其实除了审题有问题以外,还有一个问题,就是这道题的询问次数可能高达十万次,就算是用时间复杂度较低的bfs也肯定会T,为什么我这么肯定呢?因为:在这里插入图片描述

学长是用两个dfs写的,第一个dfs用来标记所有连通块,第二个dfs用来记录当前连通块中每个格子。 什么意思呢?让我们来看样例:

2 2
01
10
1 1
2 2

样例中有两次询问,第一次是1,1第二次是2,2。但是我们可以发现,第一次询问之后可以发现整个图形都是连通的,即这四个位置都是同属一个连通块的,那么我们第一次询问之后,完全可以把这四个位置的答案都记录下来,这样一来,下一次询问这一连通块的任意一个格子都不需要再进行搜索,直接输出答案即可


代码如下:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
#include <map>
#include <math.h>
#include <set>
#include <vector>
#include <stack>
#include <sstream>
#define ll long long
using namespace std;
int mov[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int vis[1005][1005];
int answ[1005][1005];//记录对应位置的答案
char mp[1005][1005];
int n, m;
int ans;
int ct;
struct node
{
    char now;
    int x, y;
} fst, sec;
queue<node> q;
void bfs()
{
    while (!q.empty())
    {

        ans++;
        fst = q.front();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int xx = fst.x + mov[i][0];
            int yy = fst.y + mov[i][1];
            if (xx < 1 || xx > n || yy < 1 || yy > n || mp[fst.x][fst.y] == mp[xx][yy] || vis[xx][yy] == ct)
                continue;
            vis[xx][yy] = ct;
            sec.now = mp[xx][yy];
            sec.x = xx;
            sec.y = yy;
            q.push(sec);
        }
    }
}
void dfs(int x, int y)
{
    answ[x][y] = ans;
    for (int i = 0; i < 4; i++)
    {
        int xx = x + mov[i][0];
        int yy = y + mov[i][1];
        if (xx < 1 || xx > n || yy < 1 || yy > n || vis[xx][yy] != ct)
            continue;
        vis[xx][yy] = 0;
        dfs(xx, yy);
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        cin >> mp[i] + 1;
    while (m--)
    {
        ct++;
        ans = 0;
        int a, b;
        cin >> a >> b;
        if (answ[a][b] != 0)
            cout << answ[a][b] << endl;
        else
        {
            while (!q.empty())
                q.pop();
            fst.now = mp[a][b];
            fst.x = a;
            fst.y = b;
            q.push(fst);
            vis[a][b] = ct;
            bfs();
            dfs(a, b);
            cout << ans << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hesorchen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值