Skip to content

Commit 6114d4e

Browse files
Add Solution.java
1 parent 6df3dbf commit 6114d4e

File tree

1 file changed

+53
-0
lines changed
  • solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
public int numPoints(int[][] darts, int r) {
5+
int n = darts.length;
6+
int maxDarts = 1;
7+
8+
for (int i = 0; i < n; i++) {
9+
for (int j = i + 1; j < n; j++) {
10+
List<double[]> centers = possibleCenters(darts[i][0], darts[i][1], darts[j][0], darts[j][1], r);
11+
for (double[] center : centers) {
12+
maxDarts = Math.max(maxDarts, countDarts(center[0], center[1], darts, r));
13+
}
14+
}
15+
}
16+
return maxDarts;
17+
}
18+
19+
private List<double[]> possibleCenters(int x1, int y1, int x2, int y2, int r) {
20+
List<double[]> centers = new ArrayList<>();
21+
double dx = x2 - x1;
22+
double dy = y2 - y1;
23+
double d = Math.sqrt(dx * dx + dy * dy);
24+
if (d > 2 * r) {
25+
return centers;
26+
}
27+
double midX = (x1 + x2) / 2.0;
28+
double midY = (y1 + y2) / 2.0;
29+
double distToCenter = Math.sqrt(r * r - (d / 2.0) * (d / 2.0));
30+
double offsetX = distToCenter * dy / d;
31+
double offsetY = distToCenter * -dx / d;
32+
33+
centers.add(new double[]{midX + offsetX, midY + offsetY});
34+
centers.add(new double[]{midX - offsetX, midY - offsetY});
35+
return centers;
36+
}
37+
38+
private int countDarts(double x, double y, int[][] darts, int r) {
39+
int count = 0;
40+
for (int[] dart : darts) {
41+
if (Math.sqrt(Math.pow(dart[0] - x, 2) + Math.pow(dart[1] - y, 2)) <= r + 1e-7) {
42+
count++;
43+
}
44+
}
45+
return count;
46+
}
47+
48+
public static void main(String[] args) {
49+
Solution solution = new Solution();
50+
System.out.println(solution.numPoints(new int[][]{{-2,0},{2,0},{0,2},{0,-2}}, 2)); // Output: 4
51+
System.out.println(solution.numPoints(new int[][]{{-3,0},{3,0},{2,6},{5,4},{0,9},{7,8}}, 5)); // Output: 5
52+
}
53+
}

0 commit comments

Comments
 (0)