I have set of rectangles ( QGraphicsRectItem in QGraphicsScene ) whose X positions are fixed and Y positions can be modified. I want to stack these rectangles if there is any overlapping. The positions of rectangles can be changed dynamically by moving/resizing those rectangles and each time it has to optimize the space such that there is no gaps. The important constraint is that , when we move a specific rectangle it has to stack the rectangles without modifying the X position of any other rectangle.
I have a simple brute force algorithm which traverse through all the rectangles and then gets the collidng rectangles , increment the Y position with some delta value for all colliding rectangles.
Any optimal solution for this problem?
You have to assign each rectangle to a level, so that on a given level, no two rectangles overlap. Correct? So allocate an array of levels, leaving room for the worst-case scenario of each level containing only one rectangle:
As you traverse your list of rectangles,
LevelFreeAt[i]will contain the time at which levelibecomes free. Now for each rectangle, in order of starting time, simply assign it to the first level that is free at its starting time, and update that level’sLevelFreeAtentry accordingly.