Imagine you have a canvas and in this canvas there are already some objects. How can you find the minimal way to cover the "uncovered" area with squares, not overlaying each other, completely filling the canvas.
In my case the "canvas" is a html-div container and the objects are nested div-containers.
Could look like this: http://www.encodechain.com/demo/200908_optimize.png
On the left there's the "start" and on the right there's on possible first "step"...
I know that there's an algorithm for this, but currently I can't remember the name.
The best I could find was this paper: Tiling a rectangle with the fewest squares.
The paper is an interesting read, though at times it delves deep into theory territory with talk of "universal constants". I am not certain whether the question of "can a rectangle of size m by n be tiled with k squares" is NP-complete. As noted in another response, your question resembles packing problems which are NP-complete. And, of course, your problem is a generalization of the one addressed in this paper, since you are dealing with non-rectangular areas. You could start by breaking your area up into the minimum number of rectangles, another interesting problem in itself. And finally, even if you could do that efficiently, I'm not sure if tiling those rectangles optimally would result in an overall optimal tiling.
As the author notes, a greedy algorithm is a good place to start: just put down the biggest square you can until the area is full.
Packing Problem
Knapsack Problem
And an article on solving 2d packing problem
Related
consider an image like this:
by grouping pixels by color into distinct rectangles, different configurations might be achieved, for example:
the goal is to find one of the best configurations, i.e. a configuration which has the least possible number of rectangles (rectangles sizes are not important).
any idea on how to design an efficient algorithm which is able to solve this problem?
EDIT:
i think the best answer is the one by #dshin, as they proved that this problem is a NP-HARD one so there probably isn't any efficient solution that is able to guarantee an optimal result.
other answers provide reasonable compromises to get an acceptable solution, but that won't always be the optimal one.
Each connected colored region is a rectilinear polygon that can be considered independently, and so your problem amounts to solving the minimum rectangle covering for rectilinear polygons. This is a well-studied problem that finds applications in some fields, like VLSI.
For convex rectilinear polygons, there is an algorithm that finds the optimal solution in polynomial time, described in this 1984 thesis.
The non-convex case is NP-hard (reference), so an efficient optimal solution likely does not exist. But there are several algorithms which produce good empirical results. This 1990 publication describes three separate algorithms, each of which are guaranteed to use at most twice as many rectangles as the optimal solution. This 2016 publication describes an algorithm that uses the common IP + LP relaxation technique, which apparently produces better results in real-life problem instances, although lacking in theoretical guarantees. Unfortunately, both publications are behind paywalls, and I haven't been able to find free resources that describe the algorithms.
If you are just looking for something reasonable, and your problem instances are not pathological in nature, then the algorithms described in other answers are probably good enough.
I don't have a proof but my feeling is a greedy approach should solve this problem:
Start on the upper left (or in whichever corner)
Expand rectangle 1px to the right as long as colors match
Expand rectangle 1px to the bottom as long as all colors in that row match
Line by line and column by column, find the next pixel that is not already part of a square (maybe keep track of visited pixels in a second array) and repeat 2 and 3.
You can switch lines and columns and go up and left or whatever instead and end up with different configurations, but from playing this through in my mind I think the number of rectangles should always be the same.
The idea here is based on the following links: Link 1 and Link 2.
In both the cases, the largest possible rectangle is computed within a given polygon/shape. Check both the above links for details.
We can extend the idea above to the problem at hand.
Steps:
Filter the image by color (say red)
Find the largest possible rectangle in the red region. After doing so mask it.
Repeat to find the next biggest rectangle until all the portions in red have been covered.
Repeat the above for every unique color.
Overview:
I have a connected shape that consists of squares put together, e.g. take a squared paper and draw a line along the existing lines that ends at its beginning and does not cross itself.
The goal is now to find an algorithm (not brute-force) that fills this shape with as few, non-overlapping rectangles as possible.
I'm looking for the optimal solution. As can be seen in the images, the naive greedy approach (take the largest rectangle) does not work.
(Optimal)
(Greedy)
My scenario is vertices reduction, but I'm sure there are other use-cases as well.
Note: This problem seems basic, but I was not able to find a solution elsewhere. Also, is this problem NP-hard?
Edit: I just realized that, in my scenario, filling the shape with as few non-overlapping triangles as possible, would give an even better result.
I've spend a lot of time researching this, since I asked the initial question. For the first problem (optimally filling the shape with rectangles), I've written the solution here under the header "Optimal Greedy Meshing":
http://blackflux.wordpress.com/2014/03/01/meshing-in-voxel-engines-part-2/
The complexity is actually better (faster) than for optimally triangulating a polygon without holes. The slowest part is the Hopcroft-Karp algorithm.
Treating the shape as a polygon is also discussed in the linked blog post. Note that I'm also considering holes.
The first problem is harder than the one with triangles; for triangles, see the algorithms in
http://en.wikipedia.org/wiki/Polygon_triangulation
which can do it without any extra vertices.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pack squares into circles?
I have a problem where I need to fit a bunch of different sized rectangles within a circle. All the rectangles must fit in the circle without overlapping each other and without overflowing the circle.
Assuming the rectangles can fit inside the circle how would one develop an algorithm to distribute them inside the circle?
All I can think of is to randomly distribute the rectangles over and over and test whether the conditions are met (brute-force).
It is a classic constraint problem, brute-force is one way to do it but there are other ways that can be better using things such as heuristics to help guide the algorithm to the solution. You would have to look up some constraint programming and bin packing papers on something like Google Scholar for some better algorithms.
Wikipedia has a good overview:
http://en.wikipedia.org/wiki/Packing_problem
As others have mentioned, an optimal solution (in say minimal area or uniform distriubtion) is likely to be NP-hard. Nevertheless, depending on your needs there are some great algorithms for packing differently sized rectangles into other rectangles. For example: Fast Optimizing Rectangle Packing Algorithm for Building CSS Sprites:
This article describes a fast algorithm to pack a series of rectangles of varying widths and heights into a single enclosing rectangle, with no overlap and in a way that minimizes the amount of wasted space in the enclosing rectangle. [...] shows step by step how the algorithm arrives at the optimal enclosing rectangle.
Note that in the above procedure the bounding rectangle is allowed to vary (nor am I convinced that the solution is the optimal enclosing rectangle). You can approximate a circle by breaking it up into discrete rectangles.
While not a complete solution to what you are looking for, I think this may be a good first step.
I've been searching far and wide on the seven internets, and have come to no avail. The closest to what I need seems to be The cutting stock problem, only in 2D (which is disappointing since Wikipedia doesn't provide any directions on how to solve that one). Another look-alike problem would be UV unwrapping. There are solutions there, but only those that you get from add-ons on various 3D software.
Cutting the long talk short - what I want is this: given a rectangle of known width and height, I have to find out how many shapes (polygons) of known sizes (which may be rotated at will) may I fit inside that rectangle.
For example, I could choose a T-shaped piece and in the same rectangle I could pack it both in an efficient way, resulting in 4 shapes per rectangle
as well as tiling them based on their bounding boxes, case in which I could only fit 3
But of course, this is only an example... and I don't think it would be much use to solving on this particular case. The only approaches I can think of right now are either like backtracking in their complexity or solve only particular cases of this problem. So... any ideas?
Anybody up for a game of Tetris (a subset of your problem)?
This is known as the packing problem. Without knowing what kind of shapes you are likely to face ahead of time, it can be very difficult if not impossible to come up with an algorithm that will give you the best answer. More than likely unless your polygons are "nice" polygons (circles, squares, equilateral triangles, etc.) you will probably have to settle for a heuristic that gives you the approximate best solution most of the time.
One general heuristic (though far from optimal depending on the shape of the input polygon) would be to simplify the problem by drawing a rectangle around the polygon so that the rectangle would be just big enough to cover the polygon. (As an example in the diagram below we draw a red rectangle around a blue polygon.)
Once we have done this, we can then take that rectangle and try to fit as many of that rectangle into the large rectangle as possible. This simplfies the problem into a rectangle packing problem which is easier to solve and wrap your head around. An example of an algorithm for this is at the following link:
An Effective Recursive Partitioning Approach for the Packing of Identical Rectangles in a Rectangle.
Now obviously this heuristic is not optimal when the polygon in question is not close to being the same shape as a rectangle, but it does give you a minimum baseline to work with especially if you don't have much knowledge of what your polygon will look like (or there is high variance in what the polygon will look like). Using this algorithm, it would fill up a large rectangle like so:
Here is the same image without the intermediate rectangles:
For the case of these T-shaped polygons, the heuristic is not the best it could be (in fact it may be almost a worst case scenario for this proposed approximation), but it would work very well for other types of polygons.
consider what the other answer said by placing the t's into a square, but instead of just leaving it as a square set the shapes up in a list. Then use True and False to fill the nested list as the shape i.e. [[True,True,True],[False,True,False]] for your T shape. Then use a function to place the shapes on the grid. To optimize the results, create a tracker which will pay attention to how many false in a new shape overlap with trues that are already on the grid from previous shapes. The function will place the shape in the place with the most overlaps. There will have to be modifications to create higher and higher optimizations, but that is the general premise which you are looking for.
Is there a standard for this? Algorithm name?
Say:
I have 10 polygons of different sizes.
I have an area of specific size.
I want to know how to fill the most polygons in that area, and how they are fitted.
Note:
Polygons may be rotated depending on the restriction set.
One possible name is a Packing Problem. It is related to the Knapsack Problem. These problems tend to be NP-hard, and many require heuristics. If you can constrain the allowed forms of polygons and of the area, there may exist a more efficient algorithm for your special case.
You can have a look at "Dancing Links" in Wikipedia for Donald Knuth's solution to the exact cover problem - which includes tiling - your question can be looked at as a tiling problem
IF (that's a big if) all your polygons were rectangles, and the area into which they are to fit is also a rectangle, then this would be called bin-packing, Google will overwhelm you with information about this. If they're not then I guess that you are looking for a variant of bin-packing, and I guess some more that you are into an NP problem for which 'try and test' is about the best algorithm around.