@@ -19,12 +19,32 @@ public class GrahamScan {
19
19
private final Stack <Point > hull = new Stack <>();
20
20
21
21
public GrahamScan (Point [] points ) {
22
+
23
+ // Validate input data
24
+ if (points == null || points .length < 3 ) {
25
+ throw new IllegalArgumentException ("At least 3 points are required to compute the convex hull" );
26
+ }
27
+
28
+ // Check if all points are the same
29
+ boolean allSame = true ;
30
+ for (int i = 1 ; i < points .length ; i ++) {
31
+ if (!points [i ].equals (points [0 ])) {
32
+ allSame = false ;
33
+ break ;
34
+ }
35
+ }
36
+
37
+ if (allSame ) {
38
+ hull .push (points [0 ]);
39
+ return ;
40
+ }
41
+
22
42
// Pre-process points: sort by y-coordinate, then by polar order with respect to the first point
23
43
Arrays .sort (points );
24
44
Arrays .sort (points , 1 , points .length , points [0 ].polarOrder ());
25
45
hull .push (points [0 ]);
26
46
27
- // Find the first point not equal to points[0] and the first point not collinear with the previous points
47
+ // Find the first point not equal to points[0]/firstNonEqualIndex and the first point not collinear firstNonCollinearIndex with the previous points
28
48
int indexPoint1 ;
29
49
for (indexPoint1 = 1 ; indexPoint1 < points .length ; indexPoint1 ++) {
30
50
if (!points [0 ].equals (points [indexPoint1 ])) {
@@ -58,11 +78,11 @@ public GrahamScan(Point[] points) {
58
78
* @return An iterable collection of points representing the convex hull.
59
79
*/
60
80
public Iterable <Point > hull () {
61
- Stack <Point > result = new Stack <>();
81
+ Stack <Point > s = new Stack <>();
62
82
for (Point p : hull ) {
63
- result .push (p );
83
+ s .push (p );
64
84
}
65
- return result ;
85
+ return s ;
66
86
}
67
87
68
88
public record Point (int x , int y ) implements Comparable <Point > {
0 commit comments