题目
方法一:DFS(超时)
算法流程:
-
枚举所有圆,对于每个圆,从圆心出发,利用DFS将圆内的格点都保存在集合中
-
利用
Set
去除重复格点,最后返回Set
大小即为出现在 至少一个 圆内的 格点数目
class Solution {
public int countLatticePoints(int[][] circles) {
int n = circles.length;
List<Grid>[] grids = new List[n];
// 1. 枚举圆,统计每个圆内的格点
for (int i = 0; i < n; i++) {
boolean[][] visited = new boolean[201][201];
grids[i] = new ArrayList<>();
dfs(circles[i][0], circles[i][1], circles[i][0], circles[i][1], circles[i][2], visited, grids[i]);
}
Set<Grid> set = new HashSet<>();
// 2. Set 去重
for(List<Grid> list : grids) {
set.addAll(list);
}
return set.size();
}
private void dfs(int x, int y, int nx, int ny, int r, boolean[][] visited, List<Grid> list) {
if (!isInCircle(x, y, r, nx, ny) || visited[nx][ny]) {
return ;
}
visited[nx][ny] = true;
list.add(new Grid(nx, ny));
// 上 右 下 左
dfs(x, y, nx - 1, ny, r, visited, list);
dfs(x, y, nx, ny + 1, r, visited, list);
dfs(x, y, nx + 1, ny, r, visited, list);
dfs(x, y, nx, ny - 1, r, visited, list);
}
private boolean isInCircle(int x, int y, int r, int nx, int ny) {
return Math.pow(nx - x, 2) + Math.pow(ny - y, 2) <= Math.pow(r, 2);
}
class Grid {
int x;
int y;
public Grid(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Grid grid = (Grid) o;
return x == grid.x &&
y == grid.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
方法二:枚举格点
枚举 200 × 200 200 \times 200 200×200范围内的所有点,并判断是否在某一个圆内
class Solution {
public int countLatticePoints(int[][] circles) {
int cnt = 0;
for (int nx = 0; nx <= 200; nx++) {
for (int ny = 0; ny <= 200; ny++) {
for (int[] c : circles) {
int x = c[0], y = c[1], r = c[2];
if (isInCircle(x, y, r, nx, ny)) {
cnt++;
break;
}
}
}
}
return cnt;
}
private boolean isInCircle(int x, int y, int r, int nx, int ny) {
return Math.pow(nx - x, 2) + Math.pow(ny - y, 2) <= Math.pow(r, 2);
}
}