#K10056. Minimum Operations to Level Terrain
Minimum Operations to Level Terrain
Minimum Operations to Level Terrain
You are given a grid representing the heights of terrain cells. Your task is to determine the minimum number of operations required to level the terrain so that all cells have the same height. In one operation, you can choose one of the distinct heights present in the grid and change all cells of that height to match another existing height. It can be shown that the minimum number of operations required is equal to \(k - 1\), where \(k\) is the number of distinct heights in the grid.
Example: For a grid with heights:
1 2 3 2 3 4 3 4 5
There are 5 distinct heights, so the answer is \(5 - 1 = 4\).
inputFormat
The input is given via standard input (stdin) and has the following format:
T m n row1 row2 ... rowm m n row1 row2 ... rowm ...
Here, the first line contains an integer T, the number of test cases. Each test case starts with two integers m and n (the number of rows and columns of the grid, respectively), followed by m lines each containing n space-separated integers representing the heights of the terrain cells.
outputFormat
For each test case, output a single integer on a new line: the minimum number of operations required to make all the cells in the grid have the same height.
## sample2
3 3
1 2 3
2 3 4
3 4 5
2 2
1 2
3 4
4
3
</p>