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

    你可能感兴趣的文章
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>