LeetCode每天刷day36:周赛133距离顺序排列矩阵单元格

版权声明:本文为博主原创文章,未经博主允许可以转载。(转呀转呀/笑哭),希望标注出处hhh https://blog.csdn.net/qq_36428171/article/details/89430912

题目:
给出 R 行 C 列的矩阵,其中的单元格的整数坐标为 (r, c),满足 0 <= r < R 且 0 <= c < C。
另外,我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。
返回矩阵中的所有单元格的坐标,并按到 (r0, c0) 的距离从最小到最大的顺序排,其中,两单元格(r1, c1) 和 (r2, c2) 之间的距离是曼哈顿距离,|r1 - r2| + |c1 - c2|。(你可以按任何满足此条件的顺序返回答案。)

提示:

1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C

题目链接:距离顺序排列矩阵单元格
C++:

class Solution {
public:
    struct node{
        int x;
        int y;
        int dis;
    };
    static bool cmp(node a, node b){
        return a.dis < b.dis;
    }
    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
        vector<node> list;
        vector<vector<int>> ret;
        for(int i = 0; i < R; i++){
            for(int j = 0; j < C; j++){
                node tmp;
                tmp.x = i;
                tmp.y = j;
                tmp.dis = abs(i - r0) + abs(j - c0);
                list.push_back(tmp);
            }
        }
        sort(list.begin(), list.end(), cmp);
        for(int i =0; i < list.size(); i++){
            vector<int> temp;
            temp.push_back(list[i].x);
            temp.push_back(list[i].y);
            ret.push_back(temp);
        }
        return ret;
    }
};

别人的简洁代码:

class Solution {
public:
    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
        vector<vector<int>> res;
        for(int i=0;i<R;i++)
            for(int j=0;j<C;j++)
                res.push_back(vector<int>{i,j});
        sort(res.begin(),res.end(),[r0,c0](vector<int>&a,vector<int>& b){
            return abs(a[0]-r0)+abs(a[1]-c0)<abs(b[0]-r0)+abs(b[1]-c0);
        });
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36428171/article/details/89430912