博客
关于我
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/

    你可能感兴趣的文章
    python系列【仅供参考】:python之subprocess模块rsync拉取文件
    查看>>
    python系列【仅供参考】:python 远程rdp
    查看>>
    python基础
    查看>>
    Python基本语法与变量类型
    查看>>
    python基本数据类型(容器)- tuple list dict set
    查看>>
    python基本工资的调整方案_Python薪资又涨了!这可咋办!
    查看>>
    Python基准测试和性能分析内存管理和垃圾回收
    查看>>
    Python基于RESTful风格的接口自动化测试实战
    查看>>
    python基于pygame实现跨年烟花效果
    查看>>
    python基于flask搭建http服务(四)—— Docker容器化部署
    查看>>
    python基于flask搭建http服务(二)—— 实现Excel上传、数据清洗、入库
    查看>>
    python基于flask搭建http服务(三)—— 使用gunicorn部署项目
    查看>>
    python基于flask搭建http服务(一)—— 实现数据查询和Excel导出
    查看>>
    Python块键盘/鼠标输入
    查看>>
    python在心理学研究中的应用有哪些_心理学在线研究可用平台简介和应用进展
    查看>>
    python系列【仅供参考】:python tornado 集成redis消息订阅的异步任务之后tornado主程序无法启动,解决方案
    查看>>
    python在使用HTMLTestRunner时,报告为空,错误提示<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf_8'>...
    查看>>
    python在gpu上运行_【python】python开启GPU加速
    查看>>
    Python在def函数中使用for循环
    查看>>
    Python在def函数中使用for循环
    查看>>