给出 R 行 C 列的矩阵,其中的单元格的整数坐标为 (r, c),满足 0 <= r < R 且 0 <= c < C。
另外,我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。
返回矩阵中的所有单元格的坐标,并按到 (r0, c0) 的距离从最小到最大的顺序排,其中,两单元格(r1, c1) 和 (r2, c2) 之间的距离是曼哈顿距离,|r1 - r2| + |c1 - c2|。(你可以按任何满足此条件的顺序返回答案。)
思路:看出规律来,就好办了
规律:很经典的代码。由于题目是算曼哈顿距离,其实每次都是一个斜着的正方形,除去本身这个点的距离是0,慢慢往外一圈一圈增加,曼哈顿距离就增加1,因此用四个while,从上顶点到右边侧点,从右边侧点到下底点,再从下底点到左侧点,最后从左侧点到上顶点。一层一层向外,直到覆盖整个矩阵即可。每次遍历的时候注意边界值即可。0 < x < R , 0 < y < C
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] arr = new int[R * C][2];
int index = 0;
arr[index][0] = r0;
arr[index++][1] = c0;
int x = r0, y = c0;
while (index < R * C) {
// 从上顶点开始
x--;
// 从上顶点到右侧点
while (x < r0) {
if (x >= 0 && y < C) {
arr[index][0] = x;
arr[index++][1] = y;
}
x++;
y++;
}
// 从右侧点到下底点
while (y > c0) {
if (y < C && x < R) {
arr[index][0] = x;
arr[index++][1] = y;
}
x++;
y--;
}
// 从下底点到左侧点
while (x > r0) {
if (x < R && y >= 0) {
arr[index][0] = x;
arr[index++][1] = y;
}
x--;
y--;
}
// 从左侧点到上顶点
while (y < c0) {
if (x >= 0 && y >= 0) {
arr[index][0] = x;
arr[index++][1] = y;
}
x--;
y++;
}
}
return arr;
}
}