当前位置: 代码迷 >> 综合 >> leetcode 1030. Matrix Cells in Distance Order
  详细解决方案

leetcode 1030. Matrix Cells in Distance Order

热度:73   发布时间:2024-01-16 17:55:19.0

leetcode 1030. Matrix Cells in Distance Order

题意:给你一个矩阵的长宽,再给你一个点的坐标,把矩阵中的每个点按距离这个点的距离排序。

思路:用结构体保存坐标和距离,再排序。

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

 

  相关解决方案