1030距离顺序排列矩阵单元格
1030距离顺序排列矩阵单元格
题目描述
给出 R 行 C 列的矩阵,其中的单元格的整数坐标为 (r, c),满足 0 <= r < R 且 0 <= c < C。
另外,我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。
返回矩阵中的所有单元格的坐标,并按到 (r0, c0) 的距离从最小到最大的顺序排,其中,两单元格(r1, c1) 和 (r2, c2) 之间的距离是曼哈顿距离,|r1 - r2| + |c1 - c2|。(你可以按任何满足此条件的顺序返回答案。)
示例 1:
输入:R = 1, C = 2, r0 = 0, c0 = 0
输出:[[0,0],[0,1]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1]
示例 2:
输入:R = 2, C = 2, r0 = 0, c0 = 1
输出:[[0,1],[0,0],[1,1],[1,0]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2]
[[0,1],[1,1],[0,0],[1,0]] 也会被视作正确答案。
示例 3:
输入:R = 2, C = 3, r0 = 1, c0 = 2
输出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2,2,3]
其他满足题目要求的答案也会被视为正确,例如 [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]。
提示:
1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C
思路
方法一 暴力法
因为题目中的数据量并不大,所以可以直接使用暴力方法求解,将每个坐标对应的曼哈顿距离求出来后对坐标点进行排序即可求出答案
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] ans = new int[R * C][];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ans[i * C + j] = new int[]{i, j};
}
}
Arrays.sort(ans,(a1,a2)->(Math.abs(a1[0]-r0)+Math.abs(a1[1]-c0))-(Math.abs(a2[0]-r0)+Math.abs(a2[1]-c0)));
return ans;
}
}
方法二 BFS
仔细分析坐标的曼哈顿距离
6 5 4 3 4 5 6
5 4 3 2 3 4 5
4 3 2 1 2 3 4
3 2 1 0 1 2 3
4 3 2 1 2 3 4
5 4 3 2 3 4 5
6 5 4 3 4 5 6
中间0为起点,每次向外扩展1,刚好和BFS是一样的,所以这里直接用BFS来做。
只要坐标点还没到达边界,就一直向外扩展,将扩展的顺序依次计入答案中即可解题。
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
Queue<int[]> que = new LinkedList<>();
boolean visited[][] = new boolean[R][C];
List<int[]> ans = new ArrayList<>();
int d[][] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
que.add(new int[]{r0, c0});
visited[r0][c0] = true;
ans.add(new int[]{r0, c0});
while (!que.isEmpty()) {
int[] tmp = que.poll();
int x = tmp[0];
int y = tmp[1];
for (int i = 0; i < 4; i++) {
int tx = x + d[i][0];
int ty = y + d[i][1];
if (tx < 0 || ty < 0 || tx >= R || ty >= C || visited[tx][ty]) {
continue;
}
int tt[] = new int[]{tx, ty};
visited[tx][ty] = true;
que.add(tt);
ans.add(tt);
}
}
return ans.toArray(new int[ans.size()][]);
}
}

浙公网安备 33010602011771号