|
| 1 | +package com.thealgorithms.geometry; |
| 2 | + |
| 3 | +/** |
| 4 | + * Utility class to check if two line segments intersect. |
| 5 | + * |
| 6 | + * <p>This class provides methods to determine whether two given line segments |
| 7 | + * intersect or not, using orientation tests. |
| 8 | + * |
| 9 | + * <p>Time Complexity: O(1) |
| 10 | + * |
| 11 | + * @author Sandeep |
| 12 | + */ |
| 13 | +public final class LineIntersection { |
| 14 | + |
| 15 | + private LineIntersection() { |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Represents a point in 2D space. |
| 20 | + */ |
| 21 | + public static final class Point { |
| 22 | + public final double x; |
| 23 | + public final double y; |
| 24 | + |
| 25 | + public Point(double x, double y) { |
| 26 | + this.x = x; |
| 27 | + this.y = y; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + private static int orientation(Point p, Point q, Point r) { |
| 32 | + double val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); |
| 33 | + if (val == 0.0) { |
| 34 | + return 0; // collinear |
| 35 | + } |
| 36 | + return (val > 0.0) ? 1 : 2; // clockwise or counterclockwise |
| 37 | + } |
| 38 | + |
| 39 | + private static boolean onSegment(Point p, Point q, Point r) { |
| 40 | + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) |
| 41 | + && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Checks whether two line segments (p1,q1) and (p2,q2) intersect. |
| 46 | + * |
| 47 | + * @param p1 starting point of first segment |
| 48 | + * @param q1 ending point of first segment |
| 49 | + * @param p2 starting point of second segment |
| 50 | + * @param q2 ending point of second segment |
| 51 | + * @return true if the segments intersect, false otherwise |
| 52 | + */ |
| 53 | + public static boolean doIntersect(Point p1, Point q1, Point p2, Point q2) { |
| 54 | + int o1 = orientation(p1, q1, p2); |
| 55 | + int o2 = orientation(p1, q1, q2); |
| 56 | + int o3 = orientation(p2, q2, p1); |
| 57 | + int o4 = orientation(p2, q2, q1); |
| 58 | + |
| 59 | + if (o1 != o2 && o3 != o4) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + |
| 63 | + if (o1 == 0 && onSegment(p1, p2, q1)) return true; |
| 64 | + if (o2 == 0 && onSegment(p1, q2, q1)) return true; |
| 65 | + if (o3 == 0 && onSegment(p2, p1, q2)) return true; |
| 66 | + if (o4 == 0 && onSegment(p2, q1, q2)) return true; |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | +} |
0 commit comments