题解:P16439 [XJTUPC 2026] 鲜艳 / 方格
jsc_want_AK_IOI · · 题解
题意简述
给定一个
解法
对每个未访问的格子进行 BFS,找出该连通块的所有格子,并记录其最小/最大行
检查矩形
::::success[AC Code]
#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;
}
::::