I have several random line segments. I have to check if there is any intersection between any two line segments. Lines may be connected or not. What would be a good algorithm for this problem?
Asked
Active
Viewed 546 times
0
-
2lines or line segments? If they are lines, then you just need to check if they are parallel. – assylias Jul 24 '12 at 10:25
-
hey,line segments not just lines. thanks anyway – A N M Bazlur Rahman Jul 24 '12 at 10:32
-
1@assylias if they are parallel they can still be equal (and thereby intersect...) – Matthias Jul 24 '12 at 10:33
-
If you're going to ask for code examples (which you're not likely to get, since the algorithms are more than a handful of LOC), at the very least mention the language you're programming in (or explicitly mention you don't care in which language). – Bart Kiers Jul 24 '12 at 10:35
-
I have found line segment code. eventually I can write my own. But I was looking, something, say, you have random 100 line segments. And each time i have to compare with two line. so permutation of 100 line segments 100P2 = 9,900 which is huge I think. I was looking for something best. Thanks anyway. – A N M Bazlur Rahman Jul 24 '12 at 10:46
-
@Matthias, assuming we're talking about Euclidean Geometry, it all depends: http://math.stackexchange.com/questions/5334/do-2-equal-lines-also-count-as-intersecting – Bart Kiers Jul 24 '12 at 10:46
-
@rokonoid, yes, the naive way to find all intersections is O(n^2), where `n` is the number of segments. However, Bentley-Ottmann will find all intersections in `O((n+k)*log(n))` where `k` is the total number of intersections (ie. the algorithm is *"input sensitive"*). – Bart Kiers Jul 24 '12 at 10:49
-
hey, -@BartKiers thanks, Bentley-Ottmann algorithm is fine. – A N M Bazlur Rahman Jul 24 '12 at 11:15
-
This is related to http://stackoverflow.com/questions/10957359/minimal-rectangle-containing-all-intersections-of-lines/10977575#10977575. – Codie CodeMonkey Jul 27 '12 at 07:20
1 Answers
4
Assuming you're talking about line segments here (otherwise, simply compare the slopes of the lines: if they have unequal slopes, they intersect).
To find out if a [single] intersection exists in a set of 2 or more line segments, you can use the Shamos-Hoey algorithm.
To find all intersections in a set of 2 or more line segments, you can use the Bentley-Ottmann algorithm.
Implementation of the two, and other "sweep-line" based algorithms, are abundantly available on the internet.

Bart Kiers
- 166,582
- 36
- 299
- 288