Amazon | Algorithm to fit images to form a collage
Anonymous User
544

We are given a canvas of size W x H.
We are also given a set of square images of size L1, L2, L3, L4, .. Ln. i.e each of the images have a dimension L1 x L1, L2 x L2, L3 x L3, L4 x L4, ... , Ln x Ln.

Design an algorithm to best fit these images into the canvas to form a collage. We can optionally scale up and scale down the images as well. Please also note that leaving blank spaces in between would not cause it to look aesthetic.

For example, say W = 5 and H = 2 and given four images of size 1x1 (let us call them I1, I2, I3, I4) ,we can generate a collage like:

1 2 3 4 5


I1 I1 | I2 I2 | I3 | A
I1 I1 | I2 I2 | I4 | B


i.e. first image is in cell A1, A2, B1, B2 (it has been scaled by a factor of two)
second image is in cell A3, A4, B3, B4 (it has been scaled by a factor of two)
third image is in cell A5
fourth image is in cell B5

But if we are given 5 such images then the above approach won't work, as it will leave an image unused. Instead it can do the following:

1 2 3 4 5


I1 I1 | I2 I3 | x | A
I1 I1 | I4 I5 | x | B


i.e. first image is in cell A1, A2, B1, B2 (it has been scaled by a factor of two)
second image is in cell A3
third image is in cell A4
fourth image is in cell B3
fifth image is in cell B4.
Space A5 and B5 are empty.
There may be more such arrangements.

Design a best fit algorithm that can place such images.
I talked about this problem being something like 2D knapsack, however I could not figure out an algorithm for this.

Can anyone please suggest what can be done? Does it match any existing problem in leetcode?

Comments (1)