社区讨论

做bfs总是RE,有没有大佬解释解释

P114101迷宫参与者 1已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@m4y63epk
此快照首次捕获于
2024/12/21 20:40
去年
此快照最后确认于
2025/11/04 12:31
4 个月前
查看原帖
做bfs的题总是会RE,这到底是为什么,按理说队列中最多也就是把整个图的点加入啊,为什么会RE呢,想不明白,像这题绝大多都RE了,就30分,然后队列开大一点就MLE
CPP
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 1010;
int n,Q;
char g[N][N];
bool st[N][N];
int blocks[N][N];
PII f[N*N];
int tt = -1,hh;
int dx[]{-1,0,1,0},dy[]{0,1,0,-1};

void bfs(int x,int y)
{
    f[++ tt] = {x,y};
    int step = 0;
    while(hh <= tt)
    {
        auto t = f[hh ++];
        st[t.first][t.second] = true;
        for(int i = 0; i < 4; i ++)
        {
            int tx = t.first + dx[i], ty = t.second + dy[i];
            if(!st[tx][ty] && tx >= 1 && tx <= n && ty >= 1 && ty <= n && g[tx][ty] == (g[t.first][t.second] ^ 1))
            {
                f[++ tt] = {tx,ty};
            }
        }
        
    }
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= n; j ++)
            if(st[i][j])step ++;
    }
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            if(st[i][j])blocks[i][j] = step;
}


int main()
{
    cin>>n>>Q;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            cin>>g[i][j];
    while(Q --)
    {
        int x,y;cin>>x>>y;
        if(blocks[x][y])cout << blocks[x][y] << endl;
        else bfs(x,y),cout << blocks[x][y] << endl;
    }
}

回复

2 条回复,欢迎继续交流。

正在加载回复...