题号:no1030
题目名:距离顺序排列矩阵单元格
原题URL:https://leetcode-cn.com/problems/matrix-cells-in-distance-order/
题目描述
给出 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]] 也会被视作正确答案。
限制
1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C
思路
题目很长,但是画个图就发现,根据公式,其实就是将中心点一层一层向外扩散,将每一层的点加入到最后的结果中
很显然就是使用bfs广度优先遍历。
1.设置一个和数组一样大的标记数组,用来记录有没有访问
2.使用简单的dfs,遍历队列出队结点的上下左右,如果没有访问,就放入队列,做下一层遍历
解题代码
public class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
//考虑使用bfs,从(r0,c0)往旁边扩散
//R行,代表int[][] 是0~R-1;C代表0~C-1
//|r1 - r2| + |c1 - c2|
int[][] res = new int[R*C][2];
int[][] isUsed = new int[R][C];
int val = 0;
//BFS由中心向外扩散,每层都判断最外层,然后进行
ArrayDeque<int[]> queue = new ArrayDeque<>();
queue.add(new int[]{r0,c0});
isUsed[r0][c0] = 1;
while (!queue.isEmpty()) {
int size = queue.size();
while(size!=0) {
int[] ints = queue.removeFirst();
res[val] = ints;
val++;
//上下左右分别是c-1,c+1,r-1,r+1,如果没有扫描过就加入下层扫描
//上
if(ints[1]-1>=0&&isUsed[ints[0]][ints[1]-1]==0) {
queue.addLast(new int[] {ints[0],ints[1]-1});
isUsed[ints[0]][ints[1]-1]=1;
}
//下
if(ints[1]+1<=C-1&&isUsed[ints[0]][ints[1]+1]==0) {
queue.addLast(new int[] {ints[0],ints[1]+1});
isUsed[ints[0]][ints[1]+1]=1;
}
//左
if(ints[0]-1>=0&&isUsed[ints[0]-1][ints[1]]==0) {
queue.addLast(new int[] {ints[0]-1,ints[1]});
isUsed[ints[0]-1][ints[1]]=1;
}
//右
if(ints[0]+1<=R-1&&isUsed[ints[0]+1][ints[1]]==0) {
queue.addLast(new int[] {ints[0]+1,ints[1]});
isUsed[ints[0]+1][ints[1]]=1;
}
size--;
}
}
return res;
}
}