Skip to content

Commit 22a8eff

Browse files
Update-2 GrahamScan.java
1 parent c9322dd commit 22a8eff

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/main/java/com/thealgorithms/geometry/GrahamScan.java

+24-4
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,32 @@ public class GrahamScan {
1919
private final Stack<Point> hull = new Stack<>();
2020

2121
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+
2242
// Pre-process points: sort by y-coordinate, then by polar order with respect to the first point
2343
Arrays.sort(points);
2444
Arrays.sort(points, 1, points.length, points[0].polarOrder());
2545
hull.push(points[0]);
2646

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
2848
int indexPoint1;
2949
for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) {
3050
if (!points[0].equals(points[indexPoint1])) {
@@ -58,11 +78,11 @@ public GrahamScan(Point[] points) {
5878
* @return An iterable collection of points representing the convex hull.
5979
*/
6080
public Iterable<Point> hull() {
61-
Stack<Point> result = new Stack<>();
81+
Stack<Point> s = new Stack<>();
6282
for (Point p : hull) {
63-
result.push(p);
83+
s.push(p);
6484
}
65-
return result;
85+
return s;
6686
}
6787

6888
public record Point(int x, int y) implements Comparable<Point> {

0 commit comments

Comments
 (0)