萌新第一天学c艹,性感BFS代码求条,70分TLE

P1141 01迷宫

2011Andy @ 2024-04-27 17:19:33

#include <bits/stdc++.h>
#define PII pair<int , int >
using namespace std;
int n , m;
queue<PII > q;
char a[1005][1005];
int mark[1005][1005];
int h[4][2] = {1 , 0 , -1 , 0 , 0 , 1 , 0 , -1};
int ans = 0;
void bfs(int x , int y){
    memset(mark , 0 , sizeof(mark));
    q.push({x , y});
    mark[x][y] = 1;
    ans++;
    while(!q.empty()){
        PII t = q.front();
        int tx = t.first , ty = t.second;
        q.pop();
        for(int i = 0 ; i < 4 ; i++){
            int dx = tx + h[i][0];
            int dy = ty + h[i][1];
            if(dx >= 1 && dx <= n && dy >= 1 && dy <= n && !mark[dx][dy] && a[dx][dy] != a[tx][ty]){
                ans++;
                mark[dx][dy] = 1;
                q.push({dx , dy});
            }
        }
    }
    cout << ans << "\n";
}
int main(){
    cin >> n >> m;
    for(int i = 1 ; i <= n ; i++){
        for(int j = 1 ; j <= n ; j++){
            cin >> a[i][j];
        }   
    }
    for(int i = 1 ; i <= m ; i++){
        int x , y;
        cin >> x >> y;
        ans = 0;
        bfs(x , y);
    }
    return 0;
}

悬关

在线等


by MuLinnnnn @ 2024-04-27 17:26:34

m 次输入中可能会有重复点,记忆化一下,算过直接输出。


by MuLinnnnn @ 2024-04-27 17:27:49

if (book[x][y] == -1){
    bfs(x,y);
}else{
    ans[i]=ans[book[x][y]];
}

book[]为记录数组


by PRew_ @ 2024-04-27 17:32:53

@Algophitronrhythm_ 也能教教我吗?Thx


by a1111111111111 @ 2024-04-27 17:32:59

《第一天会bfs》(无恶意


by 2011Andy @ 2024-04-27 17:33:50

@Algophitronrhythm_ 感谢大佬


by MuLinnnnn @ 2024-04-27 17:33:50

@nothing_exe_studio ?啥


by PRew_ @ 2024-04-27 17:44:10

@Algophitronrhythm_ 在讨论版


|