本文共 1009 字,大约阅读时间需要 3 分钟。
为了解决这个问题,我们需要找到给定矩阵中每个细胞到指定点的曼哈顿距离,并按距离从小到大排序。
#include#include using namespace std;vector > allCellsDistOrder(int R, int C, int r0, int c0) { vector > allPoints; for (int r = 0; r < R; ++r) { for (int c = 0; c < C; ++c) { int dis = abs(r - r0) + abs(c - c0); allPoints.push_back({r, c}); } } sort(allPoints.begin(), allPoints.end(), [](const pair & a, const pair & b) { return (abs(a.first - r0) + abs(a.second - c0)) < (abs(b.first - r0) + abs(b.second - c0)); }); vector > result; for (auto& p : allPoints) { result.push_back({p.first, p.second}); } return result;}
allPoints来存储所有细胞的坐标。allPoints中。std::sort函数对allPoints进行排序,排序依据是曼哈顿距离。result,每个子向量表示一个细胞的坐标。这种方法确保了我们能够高效地计算并按距离排序所有细胞的坐标。
转载地址:http://iftuz.baihongyu.com/