Hi all,
I am trying to write a program that computes the areas of intersecting rectangles. The coordinates of the rectangles are given. A rectangle may intersect another one or just stand alone.
My code is:
Rectangle class:
#include "Rectangle.h"
Rectangle::Rectangle(){
this->parent=this;
this->area=0;
this->x1=0;
this->x2=0;
this->y1=0;
this->y2=0;
this->visited=false;
}
/*
* recursive method to find the root of a rectangle object
*/
Rectangle* find(Rectangle *x){
if(x->parent == x)
return x;
else
return find(x->parent);
}
/*
* method to merge two sets if they are not already in the same set
*/
void unionSets(Rectangle * x, Rectangle * y){
y->parent=x;
}
int dfsArea(Rectangle * currentRect, int n, vector<Rectangle*> myvector, int & area, Rectangle * root){
currentRect->visited=true;
area+=(currentRect->x2-currentRect->x1)*(currentRect->y2-currentRect->y1);
if(currentRect->parent!=currentRect){
area-=(min(currentRect->x2, currentRect->parent->x2)-max(currentRect->x1, currentRect->parent->x1))*(min(currentRect->y2, currentRect->parent->y2)-max(currentRect->y1, currentRect->parent->y1));
}
// for each rect intersecting with currentRect
for(int k=0; k<n ; k++){
if(myvector[k]->visited==false && currentRect->x2 > myvector[k]->x1 && currentRect->x1 < myvector[k]->x2 && currentRect->y2 > myvector[k]->y1 && currentRect->y1 < myvector[k]->y2)
{
unionSets(currentRect, myvector[k]);
area+=dfsArea(myvector[k], n, myvector, area, root);
}
else if(find(myvector[k])==root && currentRect!=myvector[k]){ // &root?
area+=(currentRect->x2-currentRect->x1)*(currentRect->y2-currentRect->y1);
area-=(min(currentRect->x2, currentRect->parent->x2)-max(currentRect->x1, currentRect->parent->x1))*(min(currentRect->y2, currentRect->parent->y2)-max(currentRect->y1, currentRect->parent->y1));
area-=(min(currentRect->x2, myvector[k]->x2)-max(currentRect->x1, myvector[k]->x1))*(min(currentRect->y2, myvector[k]->y2)-max(currentRect->y1, myvector[k]->y1));
}
}
return area;
}
dfsArea function merges rectangles if they are intersecting and computes their total area.
My question is, am I doing it right about the parameters? Should the pointers or just the objects they (for example myvector) point to be modified? And how?
Could you please help me with this?
Thanks in advance.