1 介绍
本专题介绍曼哈顿距离如何转化为切比雪夫距离。
A点
(
x
1
,
y
1
)
(x_1,y_1)
(x1,y1)和B点
(
x
2
,
y
2
)
(x_2,y_2)
(x2,y2)的曼哈顿距离定义为它们的坐标差绝对值之和,即
∣
x
1
−
x
2
∣
+
∣
y
1
−
y
2
∣
|x_1-x_2|+|y_1-y_2|
∣x1−x2∣+∣y1−y2∣
构建投影,
(
x
′
,
y
′
)
=
(
x
+
y
,
y
−
x
)
(x',y')=(x+y,y-x)
(x′,y′)=(x+y,y−x),有
∣
x
1
−
x
2
∣
+
∣
y
1
−
y
2
∣
=
m
a
x
(
∣
x
1
′
−
x
2
′
∣
,
∣
y
1
′
−
y
2
′
∣
)
|x_1-x_2|+|y_1-y_2|=max(|x'_1-x'_2|,|y'_1-y'_2|)
∣x1−x2∣+∣y1−y2∣=max(∣x1′−x2′∣,∣y1′−y2′∣)
其中上式左边为曼哈顿距离,右边为切比雪夫距离。
2 训练
题目1:100240最小化曼哈顿距离
C++代码如下,
class Solution {
public:
int minimumDistance(vector<vector<int>>& points) {
int n = points.size();
multiset<int> sx, sy;
for (int i = 0; i < n; ++i) {
int x = points[i][0], y = points[i][1];
sx.insert(x + y);
sy.insert(y - x);
}
int res = INT_MAX;
for (int i = 0; i < n; ++i) {
int x = points[i][0], y = points[i][1];
sx.extract(x + y);
sy.extract(y - x);
int a = *sx.rbegin() - *sx.begin();
int b = *sy.rbegin() - *sy.begin();
int t = max(a, b);
res = min(res, t);
sx.insert(x + y);
sy.insert(y - x);
}
return res;
}
};