This is not a homework question :)
I have a set of rectangles scattered across an image. I want to merge (create a union) of every group of intersected rectangles. If a rectangle doesn't intersect its neighbors, it remains untouched.
The problem is that merged rectangles can intersect rectangles that were previously not in consideration; merged rectangles can also intersect newly-merged rectangles. I want to catch those cases.
So, in my mind, it needs to be iterative (try each rect against every other rect in the set) and recursive (try each merged rect against the set again, including merged rects).
How can I go about this? I'm working in Java, but this is more of an algorithmic question than a language-oriented one.
Thanks!
Edit: added relevant code to better illustrate the poor way in which I'm handling it now.
public static List<BinaryRegion> mergeRegions(List<BinaryRegion> regions)
{
List<BinaryRegion> merged = new ArrayList<BinaryRegion>();
geoModel = new GeometryFactory();
Polygon polys[] = new Polygon[regions.size()];
for (int i = 0; i < regions.size(); i++)
{
Polygon p = convertRectangleToPolygon(regions.get(i)
.getBoundingBox());
polys[i] = p;
}
System.out.println("Converted " + regions.size() + " polys");
for (int i = 0; i < regions.size(); i++)
{
System.out.println("Sending in poly " + i);
ArrayList<Polygon> result = mergePoly(polys[i], polys);
System.out.println("After run, size=" + result.size());
}
return merged;
}
private static ArrayList<Polygon> mergePoly(Polygon p, Polygon[] polys)
{
ArrayList<Polygon> merges = new ArrayList<Polygon>();
for (int i = 0; i < polys.length; i++)
{
if (p.equals(polys[i]))
System.out.println("found the exact match at " + i);
else if (p.intersects(polys[i]))
{
System.out.println("Found intersection at " + i);
System.out.println("Other poly is area "+polys[i].getArea());
Polygon u = (Polygon) p.union(polys[i]);
System.out.println("Merge size="+u.getArea());
merges.add(u);
}
else
merges.add(polys[i]);
}
return merges;
}