I have a list of overlapping rectangles. I need find a list of lists in which all the overlapping rectangles are returned. For example, in a list of 7 rectangles, if 4 rectangles are overlapped and rest are separate then a list of lists should look like this:
[0]: r1, r2, r3, r4
[1]: r5
[2]: r6
[3]: r7
I know I have to perform a hit test. I am looking for an algorithm or an example to create chains please.
Thanks
I have tried this code: Sometimes it works, sometimes, it throws index out of bound kinda exception.
while (rects.Count != 0)
{
listOfRects.Add(joinRectangles(rects, new List<Rectangle>(), rects[rects.Count - 1]));
}
private List<Rectangle> joinRectangles(List<Rectangle> rects, List<Rectangle> tempRects, Rectangle curRect)
{
for (int j = rects.Count; j-- > 0; )
{
if (hitTest(curRect, rects[j]) == true)
{
if (tempRects.Contains(rects[j]) == false)
{
tempRects.Add(rects[j]);
curRect = rects[j];
rects.Remove(rects[j]);
j--;
joinRectangles(rects, tempRects, curRect);
}
}
}
return tempRects;
}
If I supply these coordinates then I should get a list of 4 lists like this:
[0]: 1 rectangle
[1]: 3 rectangles
[2]: 1 rectangle
[3]: 1 rectangle
<?xml version="1.0" encoding="utf-16"?>
<rectangles>
<rectangle>
<X1>50.833333344375</X1>
<Y1>100</Y1>
<X2>53.833333344375</X2>
<Y2>127.00000004975</Y2>
</rectangle>
<rectangle>
<X1>136.500000033125</X1>
<Y1>100</Y1>
<X2>139.516666655625</X2>
<Y2>127.00000004975</Y2>
</rectangle>
<rectangle>
<X1>50.833333344375</X1>
<Y1>130.647222172472</Y1>
<X2>53.833333344375</X2>
<Y2>157.647222222222</Y2>
</rectangle>
<rectangle>
<X1>136.500000033125</X1>
<Y1>130.647222172472</Y1>
<X2>139.516666655625</X2>
<Y2>157.647222222222</Y2>
</rectangle>
<rectangle>
<X1>136.500000033125</X1>
<Y1>100</Y1>
<X2>139.516666655625</X2>
<Y2>157.3333333830833</Y2>
</rectangle>
<rectangle>
<X1>179.3333333775</X1>
<Y1>100</Y1>
<X2>182.3333333775</X2>
<Y2>157.3333333830833</Y2>
</rectangle>
</rectangles>