publicint[] maxPoints(int[][] grid, int[] queries) { intn= grid.length, m = grid[0].length, mn = n * m; fa = IntStream.range(0, mn).toArray(); size = IntStream.generate(() -> 1).limit(mn).toArray(); // 矩阵元素排序,第二维用来记录原始坐标 int[][] gSort = newint[mn][3]; for(inti=0; i < n; i++){ for(intj=0; j < m; j++){ gSort[i * m + j] = newint[]{grid[i][j], i, j}; } } Arrays.sort(gSort, (a, b) -> a[0] - b[0]); // 询问排序 int[] qIndexSort = IntStream.range(0, queries.length).boxed() .sorted((a, b) -> queries[a] - queries[b]) .mapToInt(Integer::valueOf) .toArray(); // 矩阵遍历指针 intj=0; int[] ans = newint[queries.length]; for(int index : qIndexSort){ while(j < mn && gSort[j][0] < queries[index]){ inta= gSort[j][1], b = gSort[j][2]; for(int[] item : help){ intnewA= a + item[0], newB = b + item[1]; if(check(newA, newB, n, m) && grid[newA][newB] < queries[index]){ union(a * m + b, newA * m + newB); } } j++; } if(grid[0][0] < queries[index]){ ans[index] = size[find(0)]; } } return ans; }
privatevoidunion(int x, int y){ x = find(x); y = find(y); if(x == y){ return; } if(size[x] < size[y]){ x = x ^ y; y = x ^ y; x = x ^ y; } fa[y] = x; size[x] += size[y]; }