曼哈顿距离就是使用d=|x1-x2|+|y1-y2|求两点间的距离
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int w, m, n;
cin >> w >> m >> n;
m --, n -- ;
int x1 = m / w, x2 = n / w;
int y1 = m % w, y2 = n % w;
if (x1 % 2 == 0) y1 = w - 1 - y1;//变一下序列的方向
if (x2 % 2 == 0) y2 = w - 1 - y2;
cout << abs(x1 - x2) + abs(y1 - y2) << endl;
return 0;
}
说到这个变序列的方向这个问题,我想到了一个题
class Solution {
public:
int passThePillow(int n, int time) {
// 计算目前是第几轮
// 注意:t 从 0 开始,所以奇偶的答案和题解中的分析是相反的
int t = time / (n - 1);
// 奇数轮,枕头从 n 传递回来
if (t & 1) return n - time % (n - 1);
// 偶数轮,枕头从 1 传递出去
else return time % (n - 1) + 1;
}
};
Code over!