#C11922. Splitting Grid into Two Special Subgrids
Splitting Grid into Two Special Subgrids
Splitting Grid into Two Special Subgrids
You are given a grid of integers. Your task is to determine whether the grid can be partitioned into exactly two special subgrids.
A special subgrid is defined as a contiguous block of cells (not necessarily connected in the usual graph‐theoretical sense) where all the numbers are equal. The two subgrids must be non-overlapping (i.e. they do not share any cell) and together they cover the entire grid.
In other words, if the grid is divided into two parts, each part must have all cells with the same value. Note that the grid is given in the form of a 2D matrix of size \(n \times m\). It is guaranteed that the input is such that the answer is "YES" only when:
- The grid does not have all cells equal.
- The grid contains exactly two distinct numbers.
- When scanning the grid in row‐major order, the moment a new number (different from the first cell) is encountered, it must be the one that forms one special subgrid.
Output "YES" if such a partition exists and "NO" otherwise.
Note: The checking procedure is defined by the following pseudo‐algorithm:
1. Let \(a\) be the number in the top left cell of the grid. 2. If all numbers in the grid are \(a\), output "NO". 3. If there are more than two distinct numbers in the grid, output "NO". 4. Otherwise, scan the grid in row‐major order. Once both distinct numbers have been seen, if the current cell is equal to \(a\), output "NO"; otherwise, output "YES".
This problem tests your ability to clearly implement the above conditions using standard input/output.
inputFormat
The first line contains an integer \(T\) representing the number of test cases. Each test case begins with a line containing two integers \(n\) and \(m\): the number of rows and columns of the grid. This is followed by \(n\) lines, each containing \(m\) integers denoting the grid values.
outputFormat
For each test case, output a single line with either "YES" or "NO" depending on whether the grid can be partitioned into two special subgrids as described.
## sample3
2 2
1 1
2 2
3 3
1 1 1
1 1 1
1 1 1
3 3
1 2 1
1 2 1
1 2 1
YES
NO
YES
</p>