DFS70分3个点T
查看原帖
DFS70分3个点T
668891
isbfpoiaewfohqaw楼主2022/7/26 20:33

求助,DFS算法70分,第2,9,10个点TLE

#include <bits/stdc++.h>
using namespace std;
struct p{
    int x, y;
}f[4];
p operator+(p a, p b){a.x += b.x;a.y += b.y;return a;}
char a[1005][1005];
bool vis[1005][1005];
queue<p> q;
int n, m, ans;
bool check(p l){
    int x = l.x, y = l.y;
    if (x < 1 || y < 1 || x > n || y > n)
        return false;
    return true;
}
void dfs(p pp){
//	vis[pp.x][pp.y] = 1;
    q.push(pp);
    while (!q.empty()){
        p now = q.front(); q.pop();
        ans++;
        for (int i = 0; i < 4; i++){
            p t1 = now + f[i], t2;
            // if (t1.x < 1 || t1.y < 1 || t1.x > n || t1.y > n) continue;
            if (check(t1) && vis[t1.x][t1.y] == 0 && (a[t1.x][t1.y] != a[now.x][now.y])){
                q.push(t1);
                vis[t1.x][t1.y] = true;
            }
        }
    }
}
int main() {
    f[0] = {0, 1};
    f[1] = {1, 0};
    f[2] = {0, -1};
    f[3] = {-1, 0};
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            cin >> a[i][j];
    while (m--){
        memset(vis, 0, sizeof(vis));
        ans = 0;
        int x, y;
        cin >> x >> y;
        vis[x][y] = 1;
        p t = {x, y};
        dfs(t);
        cout << ans << endl;
    }
}
2022/7/26 20:33
加载中...