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

    你可能感兴趣的文章
    python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
    查看>>
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>
    Python: Range() 最大尺寸;动态的还是静态的?
    查看>>
    Python: Windows下用 multiprocessing 的深坑
    查看>>
    python:Could not find platform independent libraries <prefix>解决方法
    查看>>
    Python:datetime tzinfo 时区名称文档
    查看>>
    Python:deepcopy(list) vs new_list = old_list[:]
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:Google API - 从消息中获取 mimeTypes
    查看>>
    Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
    查看>>
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>
    python:从列表中创建元组列表
    查看>>
    Python:从嵌套列表中删除重复项
    查看>>
    Python:从间隔映射到值
    查看>>
    Python:使用 shell=False 的子进程调用不起作用
    查看>>
    Python:修改 PATH 环境变量的平台无关方式
    查看>>
    Python:假与 0
    查看>>