已经用数组优化了,还是超时??
  • 板块P1141 01迷宫
  • 楼主Man_CCNU
  • 当前回复4
  • 已保存回复4
  • 发布时间2021/11/4 22:08
  • 上次更新2023/11/4 01:25:32
查看原帖
已经用数组优化了,还是超时??
524191
Man_CCNU楼主2021/11/4 22:08
#include<iostream>
#include<cstring>

using namespace std;

const int N = 1000 + 10;
char a[N][N];
int f[N][N],n, m,res;
bool ff[N][N];

int dfs(int x, int y)
{
    ff[x][y] = 1;
    int cnt = 1;
    int dx[4] = { -1,+1,0,0 }, dy[4] = { 0,0,-1,+1 };
    for (int i = 0; i <= 3; i++) {
        if (x + dx[i] >= 1 && x + dx[i] <= n && y + dy[i] >= 1 && y + dy[i] <= n) {
            if (a[x + dx[i]][y + dy[i]] != a[x][y]&&!ff[x+dx[i]][y+dy[i]]) {
                cnt += dfs(x + dx[i], y + dy[i]);
            }
        }
    }

    return cnt;
}
void setF(int x)
{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (ff[i][j]) f[i][j] = x;
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        scanf("%s", a[i] + 1);
    }
    int x = 0, y = 0;
    while (m--) {
        res = 0;
        cin >> x >> y;
        if (f[x][y]) {
            printf("%d\n", f[x][y]);
            continue;
        }
        res+=dfs(x, y);
        printf("%d\n", res);
        setF(res);
        memset(ff, 0, sizeof ff);
    }

    return 0;
}
2021/11/4 22:08
加载中...