views:

146

answers:

1

My algorithm produces a list of (usually) several thousand line segments (all 2D) which I need to join up into large polylines. These resulting polylines might be closed or open, but they are never self-intersecting. The line segments are not directed, i.e. it might be needed to flip a line segment before it can be joined to its neighbour.

What would be an extremely fast way of finding these polylines? I have to do this in real-time, so anything that takes longer than -say- 10ms is not a solution.

I'm doing this in C#, but I'm looking for ideas, not source.

+4  A: 

Would a hash of endpoints work?

If the endpoints match exactly then you can just store each object twice in a hash, once by each endpoint. Then, for each object, look up both its end points. You will get any other objects that need to be joined.

If the endpoints have any kind of imprecision, then you will need a spatial index, and probably one that uses an R-tree. You can get a similar effect by just making a 2d hash grid. The hash grid contains buckets of nearby endpoints. You will need to check neighboring cells.

DigitalRoss
Agreed. Perhaps he's having difficulty linearizing the sequence of connected points. That's easy; just store each undirected segment twice (once for each endpoint) and visit the point you didn't come from.
wrang-wrang
Oh, definitely, I wanted each object stored twice, once for each endpoint. Good point, I should have said that in so many words.
DigitalRoss
It might work. I was just wondering if there are specialised algorithms that handle this particular problem very well. The endpoints match exactly, I luckily do not have to deal with tolerance issues.ps. I'll be sure to put them in twice :)
David Rutten
It should be possible to go a lot faster than this if there are some helpful invariants. For example, is the ordering of joinable segments in any way constrained?
DigitalRoss
My 2D space is divided into rectangular cells, and each cell contains 0, 1 or 2 segments. The end-points of each segment are on the cell border.
David Rutten
Oh yeah, I populate the grid in a nested loop (first columns, then rows).
David Rutten
I suppose a sort of marching squares approach for finding nearby segments might work faster than building a hash table (ps. sorry for putting up so many comments in a row).
David Rutten
Oh, heh, you already have a 2D grid. It does seem like you know for sure which cells are the only ones that could possibly contain a matching end, and that you have, at some point, a handle on both the cell and the segment at the same time. Does the structure of the program allow you to join the line segments at that point?
DigitalRoss