博客
关于我
Weekly Contest 133
阅读量:426 次
发布时间:2019-03-06

本文共 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/

    你可能感兴趣的文章
    python20181211
    查看>>
    Python内存管理机制
    查看>>
    Python2中range 和xrange的区别??
    查看>>
    python2和3的区别
    查看>>
    python2和python3的pip版本升级
    查看>>
    python2和python3的区别
    查看>>
    python2备份交换机配置脚本
    查看>>
    Python3 - 在字符串格式化程序参数中使用变量
    查看>>
    Python3 A*寻路算法实现
    查看>>
    python3 grpc安装
    查看>>
    python3 mysql 封装多表_python3 mysql-多表查询
    查看>>
    python3 mysql8_Python MySQL8.0 错误:authentication plugin 'calling_sha2_password' is not supported....
    查看>>
    Python关键代码总览!从Zero到Hero必看的考点
    查看>>
    python3 robotframework+pycharm框架搭建
    查看>>
    Python3 shutil模块
    查看>>
    Python关于strftime函数详细解析 附实战代码
    查看>>
    Python3 tutorial day3
    查看>>
    python3 week4
    查看>>
    Python3 创建数组
    查看>>
    python3 套接字异常(a byte-like object is required not str)
    查看>>