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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/matrix-cells-in-distance-order
 

 

我的提交代码:

class Solution {

    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {

        //1.先把距离和坐标算好 距离做key, 坐标的数组做value

        HashMap<Integer, ArrayList<int[]>> map = new HashMap<>();

        for (int r = 0; r < R; r++) {

            for (int c = 0; c < C; c++) {

            int l = Math.abs(r-r0) + Math.abs(c-c0);

             if (map.containsKey(l)){

                ArrayList<int[]> lv = map.get(l);

                lv.add(new int[]{r,c});

              }else{

                ArrayList<int[]> lv = new ArrayList<>();

                lv.add(new int[]{r,c});

                  map.put(l, lv);

              }

            }

        }

 

        //2.对map根据key进行排序

        int key = 0;

        ArrayList<int[]> arrayList = new ArrayList<>();

        while (map.containsKey(key)){

            arrayList.addAll(map.get(key));

            key++;

        }

        

        //3.获得想要的数据结构

        int[][] result1 = new int[R*C][2];

        for (int i = 0; i < arrayList.size(); i++) {

            result1[i][0] = arrayList.get(i)[0];

            result1[i][1] = arrayList.get(i)[1];

        }

        return result1;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值