题解:P16439 [XJTUPC 2026] 鲜艳 / 方格
xiaozhengguoaaa · · 题解
正好用搜索水一下吧。
场上lmx大佬切了太强了。
主要思路
-
对网格进行遍历,找到未访问的格子则进行连通块搜索。
-
通过深度优先搜索遍历当前同色四连通块,统计连通块格子总数
cnt ,同时维护连通块行范围[mnr,mxr] 、列范围[mnc,mxc] 。 -
计算连通块最小包围矩形面积。
-
若
cnt\neq S ,说明连通块没有填满包围矩形,形状非矩形,无解。 -
最后输出。
:::info[AC code]
#include <bits/stdc++.h>
#define int long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 4e6 + 7;
const int MOD = 998244353;
const int INF = 0X3F3F3F3F;
const int dx[] = {-1 , 1 , 0 , 0} ;
const int dy[] = {0 , 0 , -1 , 1} ;
int n , m ;
vector<string> g ;
vector<vector<bool>> vis ;
int cnt , mnr , mxr , mnc , mxc ;
char col ;
void dfs(int x , int y)
{
vis[x][y] = 1 ;
cnt ++ ;
mnr = min(mnr , x) ;
mxr = max(mxr , x) ;
mnc = min(mnc , y) ;
mxc = max(mxc , 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)
{
continue ;
}
if (vis[nx][ny] || g[nx][ny] != col)
{
continue ;
}
dfs(nx , ny) ;
}
}
bool solve()
{
cin >> n >> m ;
g.resize(n) ;
for (int i = 0 ; i < n ; i ++)
{
cin >> g[i] ;
}
vis.assign(n , vector<bool>(m , 0)) ;
for (int i = 0 ; i < n ; i ++)
{
for (int j = 0 ; j < m ; j ++)
{
if (!vis[i][j])
{
cnt = 0 ;
mnr = mxr = i ;
mnc = mxc = j ;
col = g[i][j] ;
dfs(i , j) ;
int qwq = (mxr - mnr + 1) * (mxc - mnc + 1) ;
if (cnt != qwq)
{
return 0 ;
}
}
}
}
return 1 ;
}
signed main()
{
fst ;
int t ;
cin >> t ;
while (t --)
{
if (solve())
{
puts("Yes") ;
}
else
{
puts("No") ;
}
}
return 0 ;
}