Tuesday, June 11, 2013

Rectangle circumscribing group of smaller rectangles

Today, i am going to discuss how to find a rectangle in a plane which circumscribe the group of the rectangle in the same plane.

Eg:
       
Example1
Red Rectangle circumscribing the group of smaller rectangles 
Input will be a link list of rectangle. Each node in the link list  containing {x,y,h,w} of separate rectangle from the group of rectangles.

Output should be the {x,y,h,w} of the rectangle which tightly circumscribe the rectangles of the group.

Lets solve this step by step:

Initial 
Input to the algo

{0,0} in the plane in top left corner.

We will start with assuming the Circumscribing rectangle[ Tightly bound ] (CR) as {0,0,0,0}.

In first iteration we will make CR equal to the first rectangle that is {5,5,5,10}.

In second iteration.

  1. Find x for right most edge in new Circumscribing rectangle.

    Firstly
    #define RightEdge(RECTANGLE)  RECTANGLE ->X +RECTANGLE -> WIDTH;

    Secondly
    rightmost edge will be T= MAX( RightEdge(circumscribing Rectangle  ), RightEdge(New Rectangle)),
  2. New x coordinate of CR will be MIN of its current x and x coordinate of New Rectangle.
  3. New Width for CR will be T(from step 1) - new X coordinate of CR (calculated in step 2)
  4. Similarly y and height can also be calculated.


Code:

void RectUnion(RectT *CR, RectT *NEXTRECTANGLE)
{
int t1, t2;
// the new recatngle in the group is of negligible size
if (!NEXTRECTANGLE->w && !NEXTRECTANGLE->h)
return;

// first rectangle from the group
if (!CR->w && !CR->h) {
*CR = *NEXTRECTANGLE;
return;
}

//finding rightmost x 
t1 = CR->x + CR->w;
t2 = NEXTRECTANGLE->x + NEXTRECTANGLE->w;
if (t1 < t2)
t1 = t2;
// finding new x
if (CR->x > NEXTRECTANGLE->x)
CR->x = NEXTRECTANGLE->x;

//new width 
CR->w = t1 - CR->x;

t1 = CR->y + CR->h;
t2 = NEXTRECTANGLE->y + NEXTRECTANGLE->h;
if (t1 < t2)
t1 = t2;
if (CR->y > NEXTRECTANGLE->y)
CR->y = NEXTRECTANGLE->y;
CR->h = t1 - CR->y;
}


PS: comment if you have any confusion. For exercise you can write a program which takes input as both set of rectangle and CR and verifies the solution.