Zeroing the Grid
Time limit7sMemory limit256 MB
Find the fewest operations that zero the grid when each operation decrements two orthogonally adjacent cells by 1.
- Level
Hard8 of 10
- Topics
- Graph
- Solved
- No attempts yet
Problem
A grid filled with non-negative integers is given. You can apply the following operation to the grid as many times as you want.
- Choose two cells of the grid that are adjacent horizontally or vertically.
- For each chosen cell, decrease its value by 1 if that value is positive.
You may choose a cell that already holds 0, and that cell stays 0.
The picture below shows four consecutive operations on a 2×2 grid that turn every number into 0. The two yellow cells are the cells chosen in that step.

In this example four operations turn every number into 0, and no smaller number of operations does.
Write a program that finds the minimum number of operations needed to turn every number of the given grid into 0.
Input
The first line contains the number of test cases .
The first line of each test case contains the number of rows and the number of columns of the grid (). Each of the next lines contains the integers of that row of the grid, in column order. Each integer is between and .
Output
For each test case, print the minimum number of operations on its own line.