洛谷 P1141: 01迷宫

解法

可以发现,对于每一个连通块,答案都相同

所以每次输入一个数,如果没有访问过,那么就 DFS,否则直接输出已经记录下来的答案

时间复杂度

因为每个位置最多访问一次,所以是 \(O(n^2)\)

代码

#include <bits/stdc++.h>
#define int long long
const int N = 1005;
const int Mod = 1e9 + 7;
using namespace std;
int n, m;
char a[N][N];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int vis[N][N], ans[N * N], id;
void dfs(int x, int y)
{
    vis[x][y] = id;
    ans[id]++;
    for (int i = 0; i < 4; i++)
    {
        int tx = x + dx[i];
        int ty = y + dy[i];
        if (vis[tx][ty])
        {
            continue;
        }
        if (a[tx][ty] == a[x][y])
        {
            continue;
        }
        if (tx < 1 || tx > n || ty < 1 || ty > n)
        {
            continue;
        }
        dfs(tx, ty);
    }
}
signed main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cin >> a[i][j];
        }
    }
    while (m--)
    {
        int x, y;
        cin >> x >> y;
        if (!vis[x][y])
        {
            id++;
            dfs(x, y);
            cout << ans[id] << endl;
        }
        else
        {
            cout << ans[vis[x][y]] << endl;
        }
    }
    return 0;
}
posted @ 2025-05-09 21:55  jackzhang2013  阅读(27)  评论(0)    收藏  举报