Chaos City has grown out of control. Building have been built everywhere and the city layout is a complete mess. The mayor decided that this must come to an end, and wants to create a nice, structed city.
After some research, he found the ideal way to make this happen. Inspired by the New York district of Manhanttan, he wants all buidlings organized in a rectangular grid, separated by avenuesrunning from North to South and streets running from West to East. These streets and avenues should all be separated by the same distance D.
In the current situation, the buidlings are already organized in a rectangular grid. In fact each buidling fills exactly one square in this grid. However, with all the buildings randomly scattered across the city, it may be impossible to build the roads without demolishing a couple of buildings. To keep most citizens happy, the mayor wants to demolish as few buidlings as possible. Given the current locations of the buidlings, what's this minimum number?
The above picture illustrates the problem. The shaded squares are the initial locations of the buidlings. If the roads should be separated by a distance of three, the thick lines indicate the optimal placement of the roads and one building has to be demolished.