|
| 1 | +package com.thealgorithms.geometry; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * A Java program that determines whether a point is inside a polygon using the Ray Casting algorithm. |
| 8 | + * The time complexity is O(n), where n is the number of vertices in the polygon. |
| 9 | + * The space complexity is O(1). |
| 10 | + * |
| 11 | + * References: |
| 12 | + * https://en.wikipedia.org/wiki/Point_in_polygon |
| 13 | + */ |
| 14 | +public class RayCasting { |
| 15 | + |
| 16 | + /** |
| 17 | + * Determines if the given point is inside the polygon. |
| 18 | + * |
| 19 | + * @param polygon An array of points representing the vertices of the polygon. |
| 20 | + * @param point The point to check. |
| 21 | + * @return true if the point is inside the polygon, false otherwise. |
| 22 | + */ |
| 23 | + public static boolean isPointInPolygon(Point[] polygon, Point point) { |
| 24 | + int n = polygon.length; |
| 25 | + boolean inside = false; |
| 26 | + |
| 27 | + for (int i = 0, j = n - 1; i < n; j = i++) { |
| 28 | + if ((polygon[i].y > point.y) != (polygon[j].y > point.y) && |
| 29 | + (point.x < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / |
| 30 | + (polygon[j].y - polygon[i].y) + polygon[i].x)) { |
| 31 | + inside = !inside; |
| 32 | + } |
| 33 | + } |
| 34 | + return inside; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * A record representing a point in 2D space. |
| 39 | + */ |
| 40 | + public record Point(int x, int y) { |
| 41 | + /** |
| 42 | + * @return A string representation of this point in the format (x, y) |
| 43 | + */ |
| 44 | + @Override |
| 45 | + public String toString() { |
| 46 | + return String.format("(%d, %d)", x, y); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) { |
| 51 | + Point[] polygon = { |
| 52 | + new Point(0, 0), |
| 53 | + new Point(5, 0), |
| 54 | + new Point(5, 5), |
| 55 | + new Point(0, 5) |
| 56 | + }; |
| 57 | + Point testPoint = new Point(3, 3); |
| 58 | + System.out.println("Is point " + testPoint + " inside the polygon? " + isPointInPolygon(polygon, testPoint)); // true |
| 59 | + |
| 60 | + Point outsidePoint = new Point(6, 3); |
| 61 | + System.out.println("Is point " + outsidePoint + " inside the polygon? " + isPointInPolygon(polygon, outsidePoint)); // false |
| 62 | + } |
| 63 | +} |
0 commit comments