跳到正文

题解

题解:P16439 [XJTUPC 2026] 鲜艳 / 方格

jsc_want_AK_IOI约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年5月10日
收录
2026年5月11日
更新
2026年11月14日
篇幅
约 4 分钟
题目
P16439

版本

  1. v2当前
  2. v1

题意简述

给定一个 n×mn\times m 的 01 网格,判断每个同色连通块是否都是矩形。

解法

对每个未访问的格子进行 BFS,找出该连通块的所有格子,并记录其最小/最大行 r1,r2r_1,r_2 和最小/最大列 c1,c2c_1,c_2。 检查矩形 [r1,r2]×[c1,c2][r_1,r_2]\times[c_1,c_2] 内是否全为同色,若不是则输出 No\texttt{No},否则继续。

AC Code
C++
#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<string> g;
bool vis[505][505];

int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};

bool bfs(int sx, int sy)
{
    char ch = g[sx][sy];
    queue<pair<int, int>> q;
    q.push({sx, sy});
    vis[sx][sy] = true;

    int r1 = sx, r2 = sx, c1 = sy, c2 = sy;
    vector<pair<int, int>> v;

    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        v.push_back({x, y});

        if (x < r1) r1 = x;
        if (x > r2) r2 = x;
        if (y < c1) c1 = y;
        if (y > c2) c2 = y;

        for (int d = 0; d < 4; d++)
        {
            int nx = x + dx[d];
            int ny = y + dy[d];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && g[nx][ny] == ch)
            {
                vis[nx][ny] = true;
                q.push({nx, ny});
            }
        }
    }

    for (int i = r1; i <= r2; i++)
        for (int j = c1; j <= c2; j++)
            if (g[i][j] != ch) return false;
    return true;
}

void solve()
{
    cin >> n >> m;
    g.resize(n);
    for (int i = 0; i < n; i++)
        cin >> g[i];

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            vis[i][j] = false;

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (!vis[i][j])
                if (!bfs(i, j))
                {
                    cout << "No\n";
                    return;
                }
    cout << "Yes\n";
}

int main()
{
    int T;
    cin >> T;
    while (T--) solve();
    return 0;
}
原文