力扣题解(1030. 距离顺序排列矩阵单元格),带注释

题目描述

链接:点我

注意:多看几遍题目,开始没看懂…相当于计算矩阵网格里面的点(不要计算边界) 我开了题解才明白题的意思 orz…

题解

class Solution {
    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        int ans[][] = new int[rows*cols][]; // 是一个二维整数数组,用于存储排序后的单元格坐标。
        for(int i = 0;i<rows;i++){
            for(int j=0;j<cols;j++)
                //将矩阵中的每个单元格的行索引 i 和列索引 j 存储在 ans 数组的相应位置上,从而形成一个具有二维坐标信息的数组。
                ans[cols*i + j] = new int[]{i,j}; //
        }
        // 自定义数组排序  参考:https://blog.csdn.net/qq_45733304/article/details/124350468
        Arrays.sort(ans, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
            	//升序排列  下标0表示行,1表示列
                return (Math.abs(o1[0] - rCenter) + Math.abs(o1[1] - cCenter))-(Math.abs(o2[0] - rCenter) + Math.abs(o2[1] - cCenter));  
            }
        });

        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值