---
id: 68
lang: en
translation_of: index.md
source_sha256: dc92b9a47a21f10cac8ad804f94fdc8853a69aaf2a86c0adf54e6e01299039bf
title: "P1141: 01 Maze — Solution"
description: "Solving the 01 maze with an extended disjoint-set union that adds up component sizes, plus mapping each cell (x, y) to a single number."
tags: ["Search","BFS","P1141","Luogu"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "连通块个数 rendered literally as “connected-component counts” (the code sums the sizes of the components)."
---

## Approach

After thinking about it for a long time <del>(actually, understanding the solution)</del>, I worked out how to solve this problem. It is mainly an extension of the disjoint-set union plus some preprocessing. While reading in the 01 maze, we check whether the point on the left and the point on the right are connected. If they are, we merge them in the DSU, and **just add up the connected-component counts in the DSU**.

Another main idea is <strong>mapping.</strong> In the DSU our array is one-dimensional (`mem[]`), so we only need a function that converts (`x,y`) into a number. (Specifically: `ret = x*n + y;`)

## Code

```cpp
// P1141_ufs.cpp
#include <iostream>

using namespace std;

const int maxm = 10000000;
const int maxn = 1010;
char map[maxn][maxn];
int n, m;

struct UFS
{
    int mem[maxm];
    int mem_h[maxm];

    UFS()
    {
        for (int i = 0; i < maxm; i++)
            mem[i] = i, mem_h[i] = 1;
        for (int i = maxm; i < maxn; i++)
            mem_h[i] = 1;
    }

    int Find(int a)
    {
        if (mem[a] == a)
            return a;
        return mem[a] = Find(mem[a]);
    }

    void Unite(int a, int b)
    {
        if (Find(a) != Find(b))
            mem_h[Find(a)] += mem_h[Find(b)], mem[Find(b)] = Find(a);
    }
} u;

int hashcode(int a, int b)
{
    return a * n + b;
}

int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        {
            cin >> map[i][j];
            // left;
            if (j != 1 && map[i][j - 1] != map[i][j])
                u.Unite(hashcode(i, j), hashcode(i, j - 1));
            // up;
            if (i != 1 && map[i - 1][j] != map[i][j])
                u.Unite(hashcode(i, j), hashcode(i - 1, j));
        }
    for (int i = 0; i < m; i++)
    {
        int a, b;
        cin >> a >> b;
        cout << u.mem_h[u.Find(hashcode(a, b))] << endl;
    }
    return 0;
}
```

I like heavy formatting for my code (vscode), so the line count may be on the high side.
