Leetcode 1030. Matrix Cells in Distance Order
题目链接: Matrix Cells in Distance Order
难度:easy
题目大意:
给一个矩阵的行数和列数,并给出矩阵上某个元素的行坐标与列坐标,计算矩阵所有元素到这个元素的距离,将这些元素按距离升序排列,输出这些元素的行坐标与列坐标。
思路:
思路1:
计算矩阵上各个元素到特定点的距离,然后排序。
思路2(参考高赞回答):
以特定点为中心,除这个点外,这个点上下左右是离它最近的点,然后再以这四个点分别作为中心,向外扩展。用Queue来实现。
代码
思路1:
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] index=new int [R*C][2];//记录矩阵各个元素的行下标和列下标
int count=0;
for(int i=0;i<R;i++){
for(int j=0;j<C;j++){
index[count][0]=i;
index[count][1]=j;
count++;
}
}
Arrays.sort(index,(o1,o2)->Math.abs(o1[0]-r0)+Math.abs(o1[1]-c0)-(Math.abs(o2[0]-r0)+Math.abs(o2[1]-c0)));
return index;
}
}
思路2:
class Solution {//高赞回答
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] res=new int [R*C][2];
boolean[][] visited=new boolean[R][C];
int i=0;
Queue<int[]> queue=new LinkedList<int[]>();
queue.offer(new int[]{r0,c0});
while(!queue.isEmpty()){
int[] cell=queue.poll();
int r=cell[0];
int c=cell[1];
if(r<0||r>=R||c<0||c>=C){
continue;
}
if(visited[r][c]){
continue;
}
res[i++]=cell;
visited[r][c]=true;
queue.offer(new int[]{r-1,c});
queue.offer(new int[]{r+1,c});
queue.offer(new int[]{r,c-1});
queue.offer(new int[]{r,c+1});
}
return res;
}
}