Reputation: 7961
I have implemented this algorithm to generate a list of neighboring polygons for each polygon. The implementation works fine.
Now I intend to generate a list of polygon clusters. Each cluster contains common neighbors:
I'm a bit confused trying to come up with an algorithm to merge common neighbors into clusters. Is there any standard algorithm to do so?
Upvotes: 0
Views: 203
Reputation: 46960
This is a classical disjoint set union-find problem. The union-find algorithm and its related data structure support three operations:
Now execute the following algorithm:
for each polygon p
MakeSet(p)
for each polygon p
for each polygon q that's a neighbor of p
Union(p, q)
Let m be a map from polygons to lists of polygons, intitially empty
for each polygon p
append p to map[Find(p)]
Now the values (lists of polygons) in the map are your answer.
The Union-Find algorithm with union by rank and collapsing find is essentially constant time (read the Wikipedia article for the theoretical details of the inverse Ackermann function), very fast in practice, and easy to implement. All the map operations are also constant time.
Consequently, this algorithm runs with speed (essentially) proportional to the sum of the input lists of polygons; about as fast as possible.
Upvotes: 1
Reputation: 889
This is generally accomplished using either a depth-first search or a breadth-first search.
In the case of a BFS, you could do something like the following:
Create an empty queue, and assign all polygons to group -1. Set the current group to 0
While there are any polygons in group -1:
Randomly grab a polygon which is in group -1 and add it to the queue
While the queue is not empty:
Grab the first polygon in the queue and assign it to the current group
Find all of that polygon's neighbors
For all of the neighbors, if they are in group -1, add them to the queue
Remove the selected polygon from the queue
Increment the current group
When this algorithm completes, each polygon will be assigned to a cluster of connected components.
Upvotes: 0