Leveling the Tiles
Time limit5sMemory limit512 MB
Given a grid of heights, each impact lowers one tile and all tiles connected to it at the same height; find the minimum impacts to make every tile equal.
Problem
Mirko owns an uneven plot of land that measures meters and is paved with tiles of size meter. The ground is uneven, so every tile has its own height, given in centimeters.
Two tiles are adjacent if they share a side. A tile has at most four adjacent tiles. Two tiles are connected if you can walk from the first to the second, moving in each step from the current tile to an adjacent tile of the same height.
A storm starts dropping large chunks of ice on the land. When a chunk lands on a tile, the impact pushes that tile down by 1 centimeter, and every tile connected to it goes down by 1 centimeter as well.
Compute the smallest number of ice chunks that can fall so that all tiles end up at the same height. Each chunk falls at a different moment and lands on exactly one tile.
Input
The first line contains two natural numbers and , the dimensions of the land. ()
Each of the next lines contains natural numbers, the heights of the corresponding tiles in centimeters. Every height is between and .
Output
Print the minimum number of ice impacts after which all tiles have the same height.
Hint
In the first example, after one chunk lands on the middle tile, every tile except the last one has height 2. After one more chunk lands on the middle tile, all tiles have height 1.