由于涉及到复杂对象的比较,我们可以新建一个灯对象(Lamp),它有三个属性,X代表中心点横坐标,Y代表中心点的纵坐标,R代表半径。将每行输入转为一个灯,并放入集合list中为了寻找基准灯,也就是最高和最左边的灯,可以对Lamp对象自定义比较方法,取Y最小的(Y相等时取X最小的)对list按照我们自定义规则进行排序(最高最左的在前)对排序后list的第一个灯,作为基准灯,找到和基准灯在同一行的灯。判断同一行的标准,两个灯纵坐标的差值的绝对值<=灯半径。这个比较方法可以直接写在我们新建的Lamp对象中。对与基准灯同一行的灯,加入到一个临时集合tmp,然后再对tmp排序,按从左到右排序即可(X越小排在越前)将本轮排序结果tmp加入最终的ans中继续寻找下一个基准灯(还未被加入到ans中的里面找最高最左的灯),重复4,5,6,7步骤。 题解 package hwod; import java.util.*; public class AIBoardRecognize { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] matrix = new int[n][5]; for (int i = 0; i < n; i++) { for (int j = 0; j < 5; j++) { matrix[i][j] = sc.nextInt(); } } List res = aIBoardRecognize(matrix); for (int i = 0; i < res.size(); i++) { if (i != 0) System.out.print(""); System.out.print(res.get(i).getId()); } } private static List aIBoardRecognize(int[][] matrix) { int m = matrix.length; List lamps = new ArrayList<>(m); for (int i = 0; i < m; i++) { int id = matrix[i][0]; int x = (matrix[i][1] + matrix[i][3]) >> 1; int y = (matrix[i][2] + matrix[i][4]) >> 1; int r = (matrix[i][3] - matrix[i][1]) >> 1; lamps.add(new Lamp(id, x, y, r)); } Collections.sort(lamps); List ans = new ArrayList<>(m); int i = 0; while (i < m) { Lamp base = lamps.get(i); List tmp = new ArrayList<>(); while (i < m && base.isSameHigh(lamps.get(i))) { tmp.add(lamps.get(i)); i++; } Collections.sort(tmp, (o1, o2) -> o1.getX() - o2.getX()); ans.addAll(tmp); } return ans; } } class Lamp implements Comparable { private int id; private int x; private int y; private int r; public Lamp(int id, int x, int y, int r) { this.id = id; this.x = x; this.y = y; this.r = r; } public int getId() { return id; } public int getX() { return x; } public int getY() { return y; } public int getR() { return r; } public boolean isSameHigh(Lamp lamp) { return Math.abs(lamp.getY() - this.getY()) <= this.r; } @Override public int compareTo(Lamp other) { return this.getY() == other.getY() ? this.getX() - other.getX() : this.getY() - other.getY(); } }