I'm working on a project which involves packing multiple rectangles in a larger rectangle(the bounding box). Rectangles can't overlap with each other or with the boundaries of the bounding box. Rectangles can rotate, increasing the state space to n! * 2^n
for problems of n rectangles.
I'm trying to write a Python program that 'solves' these problems, eg it should find all possible solutions given a set of rectangles and a bounding box. I'm using a depth-first search algorithm right now, but I feel like I'm missing a lot of optimisations to speed up my program. My algorithm works as follows:
- I have a list with values representing the heights of the columns in the larger bounding box, initialised to all 0's.
- I look for the first empty spot in the bounding box, which is represented by the column with the smallest value.
- If the current rectangle fits in that spot, I 'place' the rectangle by increasing the height of the right columns by the height of the rectangle.
- Repeat 2 and 3 until no more rectangles can be fit and backtrack to other possible solutions.
In (pseudo-)code it looks like this:
def solve(rectangles):
# Solution found
if rectangles is empty:
add_to_solutions()
return
position = find_first_empty_spot()
for rectangle in rectangles:
for r in [rectangle, rectangle.rotated()]:
if rectangle fits at given position:
place_rectangle_in_bounding_box(r)
remove r from rectangles
solve(remaining_rectangles)
remove_rectangle_from_bounding_box(r)
Are the basics of my algorithm correct or am I missing some (obvious) improvements? It would be great to solve problems of sizes up to 20 rectangles but my current algorithm would take way too much time to solve them.
And: I'm trying to find 'all' possible solutions to the problem, I can't just stop after finding 'a' solution, so a lot of heuristics found in the literature are not applicable.