Skip to content

Commit 3292fb6

Browse files
Add LineSegmentIntersection class for intersection detection
Implement line segment intersection detection using orientation method.
1 parent ca16e4e commit 3292fb6

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.geometry;
2+
3+
/**
4+
* Line Segment Intersection detection using orientation method.
5+
*
6+
* Time Complexity: O(1)
7+
*/
8+
public final class LineSegmentIntersection {
9+
private LineSegmentIntersection() {}
10+
11+
public static boolean doIntersect(Point p1, Point q1, Point p2, Point q2) {
12+
int o1 = Point.orientation(p1, q1, p2);
13+
int o2 = Point.orientation(p1, q1, q2);
14+
int o3 = Point.orientation(p2, q2, p1);
15+
int o4 = Point.orientation(p2, q2, q1);
16+
17+
if (o1 != o2 && o3 != o4) return true;
18+
19+
// Collinear cases
20+
if (o1 == 0 && onSegment(p1, p2, q1)) return true;
21+
if (o2 == 0 && onSegment(p1, q2, q1)) return true;
22+
if (o3 == 0 && onSegment(p2, p1, q2)) return true;
23+
if (o4 == 0 && onSegment(p2, q1, q2)) return true;
24+
25+
return false;
26+
}
27+
28+
private static boolean onSegment(Point p, Point q, Point r) {
29+
return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x)
30+
&& q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
31+
}
32+
}

0 commit comments

Comments
 (0)