跳到正文

题解

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

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

文章信息

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

版本

  1. v1当前

正好用搜索水一下吧。

场上lmx大佬切了太强了。

主要思路

  • 对网格进行遍历,找到未访问的格子则进行连通块搜索。

  • 通过深度优先搜索遍历当前同色四连通块,统计连通块格子总数 cntcnt,同时维护连通块行范围 [mnr,mxr][mnr,mxr]、列范围 [mnc,mxc][mnc,mxc]。

  • 计算连通块最小包围矩形面积。

  • 若 cnt≠Scnt\neq S,说明连通块没有填满包围矩形,形状非矩形,无解。

  • 最后输出。

AC code
C++
#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 ;
}
原文