Leetcode 1030. Matrix Cells in Distance Order(分别用sort排序和Queue实现)

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;
    }
}

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值