find smallest area that contains all the rectangles

后端 未结 3 701
梦如初夏
梦如初夏 2020-12-16 19:37

This is an interview question.
We are given dimensions of various rectangles, we have to find out the area(minimum) of rectangle that can enclose all of them? rectangles

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 19:48

    First of all you should check, could be enclosing rectangle be rotated or no? Anyway, you could ignore "rectangles" condition and resolve task in points. You have array of points (which are vertexes of rectangles). Your task is to find encosing rectangle with minimum area. If enclosing rectangle could not be rotated then solution is silly and has complexity O(n).

    Generated array of rectangles and make array of points, which are vertexes of rectangles. Next is simple:

    long n; // Number of vertexes
    point arr[SIZE]; //Array of vertexes
    long minX = MAXNUMBER, minY = MAXNUMBER, maxX = -MAXNUMER, maxY = -MAXNUMBER;
    for (long i = 0; i < 4 * n; i++)
    {
        minX = MIN(minX, arr[i].x);
        minY = MIN(minY, arr[i].y);
        maxX = MIN(maxX, arr[i].x);
        maxY = MIN(maxY, arr[i].y);
    }
    long width = maxX - minX, height = maxY - minY;
    printf("%ddX%ld", width, height);
    

    Another task if rectangle could be rotated. Then you should first:

    1. Build minimum convex polygon of all the points in rectangle. You can use any of existing algorythms. Complexity O(n log n). As exmaple "Graham's Scan" : http://en.wikipedia.org/wiki/Graham%27s_scan
    2. Use simple algorithm for convex polygon. Link: http://cgm.cs.mcgill.ca/~orm/maer.html

    Link for your task in wiki: http://en.wikipedia.org/wiki/Minimum_bounding_rectangle

提交回复
热议问题