To solve this problem, we need to determine if we can transform a given grid of 0s and 1s into an all-zero grid using the minimum number of operations. Each operation involves flipping all four cells in a 2x2 subgrid.
Approach
- Edge Case Handling: If the grid has fewer than 2 rows or 2 columns, no operations can be performed. Thus, the grid must already be all zeros to be valid.
- Grid Transformation: Process the grid from the top-left to the bottom-right. For each cell (i, j) in the grid (up to the second-last row and column), if the cell value is 1, flip the 2x2 subgrid starting at (i, j) and increment the operation count.
- Validation: After processing all possible 2x2 subgrids, check if all cells in the grid are zero. If yes, the transformation is possible; otherwise, it is not.
Solution Code
n, m = map(int, input().split())
grid = []
for _ in range(n):
row = list(map(int, input().split()))
grid.append(row)
if n < 2 or m < 2:
# No possible operations, check if all are zero
all_zero = True
for row in grid:
if any(cell == 1 for cell in row):
all_zero = False
break
if all_zero:
print("Yes")
print(0)
else:
print("No")
print(0)
else:
# Create a copy of the grid to modify
grid_copy = [row[:] for row in grid]
count = 0
# Process each possible 2x2 square
for i in range(n-1):
for j in range(m-1):
if grid_copy[i][j] == 1:
count += 1
# Flip the 2x2 square
grid_copy[i][j] ^= 1
grid_copy[i][j+1] ^= 1
grid_copy[i+1][j] ^= 1
grid_copy[i+1][j+1] ^= 1
# Check if all cells are zero
valid = True
for row in grid_copy:
if any(cell == 1 for cell in row):
valid = False
break
if valid:
print("Yes")
print(count)
else:
print("No")
print(0)
Explanation
- Edge Case Handling: For grids with fewer than 2 rows or columns, we directly check if all cells are zero since no operations can be done.
- Grid Transformation: We iterate over each cell (i, j) where a 2x2 subgrid starting at (i, j) is valid. If the cell is 1, we flip the subgrid to turn it into 0, as this is the only way to correct the cell without affecting already processed cells.
- Validation: After processing all valid subgrids, we check if all cells are zero. If they are, the transformation is possible with the counted operations; otherwise, it is impossible.
This approach ensures that we use the minimum number of operations since we only flip a subgrid when necessary, and once processed, cells are not touched again. The complexity is O(n*m), which is efficient for typical grid sizes.


作者声明:本文包含人工智能生成内容。