• leetcode- 距离顺序排序矩阵单元格


    C++解法:

    
    #include <iostream>
    #include <vector>
    #include <map>
    #include <algorithm>
    
    using namespace std;
    
    
    class Solution {
    public:
        vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
            vector<vector<int>> res(R*C, vector<int>(3));//数组第三个位置存放两点的曼哈顿距离
            int num = 0;
            for (int i = 0; i<C; i++)
            {
                for (int j = 0; j<R; j++)
                {
                    res[num][0] = j;
                    res[num][1] = i;
                    res[num][2] = abs(r0 - j) + abs(c0 - i);//曼哈顿距离
                    num++;
                }
            }
            sort(res.begin(), res.end(), ismax);//排序
            for (int i = 0; i<num; i++)//将曼哈顿距离删除
            {
                res[i].pop_back();
            }
            return res;
        }
        static bool ismax(vector<int> &a, vector<int> &b)//根据曼哈顿距离升序排序
        {
            return a[2]<b[2];
        }
    };
    
    
    int main()
    {
        Solution m;
        m.allCellsDistOrder(1, 2, 0, 0);
        
        return 0;
    }

    Python解法:

    def allCellsDistOrder(R, C, r0, c0):
        dist_list = [[] for i in range(R+C)]
        for i in range(R):
            for j in range(C):
                distinct = abs(r0 - i) + abs(c0 - j)
                dist_list[distinct].append([i, j])
        result = []
        for i in dist_list:
            if i:
                result.extend(i)
            else:
                break
        return result
    
    
    print(allCellsDistOrder(2, 3, 1, 2))
    Try to be a giver
  • 相关阅读:
    event对象之与onmouse相关的事件触发
    对文档树进行导航
    event对象的onkeydown使用
    event的onchange方法
    函数名-函数参数坑-迭代器
    函数进阶-名称空间
    初识函数
    文件管理
    基础数据类型补充-编码进阶
    集合-缓存机制-深浅copy
  • 原文地址:https://www.cnblogs.com/HannahGreen/p/12097355.html
Copyright © 2020-2023  润新知