zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    php foreach的使用注意
    php数组遍历 使用foreach
    PHP strip_tags() 函数
    php nl2br() 函数
    php文件上传
    一个网站雏形
    jsp接收相同复合参数 request.getParameterValues()用法
    使用div+css制作简单导航 以及要注意问题
    Java 类与对象
    java 基础
  • 原文地址:https://www.cnblogs.com/HannahGreen/p/12097355.html
Copyright © 2011-2022 走看看