Simplified, I have to solve the following problem:
You have a 2-dimensional array filled with 0s and 1s. Find the minimum number of rectangles such that they cover all 1s. Rectangles should not overlap.
The function signature might look like:
List<Rectangle> FindCoveringRectangles(bool[,] array)
I already have a solution that is "good enough" but doesn't always find the minimum number of rectangles. I'd like to know if there is some well known and efficient algorithm that can be applied to solve this problem?
Example:
An input array of:
..........
.1.....11.
.......11.
...111....
...111....
...111....
....1111..
....1111..
......11..
..........
(0s replaced by dots for readability)
Might result in the following rectangles:
(2,2,2,2),
(2,8,3,9),
(4,4,6,6),
(7,5,8,8),
(9,7,9,8)
(top, left, bottom, right), 1-based
There can be more than one solution, but one is enough.
This is a matching problem of a kind, that could easily have shown NP-hard. However it seems there is actually a very fast solution!
Using a bfs flood-fill you can find each connected component, O(n)
. Hence wlog we can assume that we just have to fill one connected area.
If the area doesn't have holes in it, you can use the algorithm described in this paper (or here on google scholar.)
An O(n log log n) algorithm is proposed for minimally rectangular partitioning a simple rectilinear polygon. For any simple rectilinear polygon P, a vertex-edge visible pair is a vertex and an edge that can be connected by a horizontal or vertical line segment that lies entirely inside P. It is shown that, if the vertex-edge visible pairs are found, the maximum matching and the maximum independent set of the bipartite graph derived from the chords of a simple rectilinear polygon can be found in linear time without constructing the bipartite graph. Using this algorithm, the minimum partition problem for convex rectilinear polygons and vertically (horizontally) convex rectilinear polygons can be solved in O(n) time
Some of the papers referred to also cover the case of an area with holes. These run in O(n^(3/2)logn) though, but they still seam pretty good.
Alternatively, one thing you might do is solving the problem without holes, solving the problem for each hole, and then subtract. This might not give an optimal solution though, but would keep the runtime.
You could also try and split the shape in its different topological parts, but that would likely run exponentially in the number of holes.
Thirdly you could try to adapt the proposed algorithm for the more general case, but it might be hard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With