1030. Matrix Cells in Distance Order

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
int[][] res = new int[rows * cols][2];
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
res[index++] = new int[]{i, j};
}
}

Arrays.sort(res, (o1, o2) -> {
int distance1 = Math.abs(o1[0] - rCenter) + Math.abs(o1[1] - cCenter);
int distance2 = Math.abs(o2[0] - rCenter) + Math.abs(o2[1] - cCenter);
return Integer.compare(distance1, distance2);
});

return res;
}
}

References

1030. Matrix Cells in Distance Order