解决这个问题的一种方法是创建一个包含所有点的数组,其中的数据指示每个点的路径索引、位置索引和位置。
接下来,按位置对数组进行排序,并丢弃被同一路径上的点包围的项目,因为这些项目肯定不会构成最佳对。
然后对于排序数组中的每个点,计算到具有较高位置的不同路径上最近点的距离(无需考虑较低的位置,因为相应的配对已经在外循环的较早时考虑过) .由于排序后的过滤,每个项目最多会与其他两个项目进行比较(可能一个来自同一路径,一个来自不同路径)。
解决方案将O(n log n) 与点数(来自排序,然后是O(n) 过程)缩放,如果需要考虑很多点,这可能很有用。
这是一个用 Javascript 实现的示例。
const paths = [
[17, 32, 71, 91],
[15, 12, 25, 39, 7],
[52, 63, 9, 29, 49, 37],
[43, 40, 5]
]
// Add [path_idx, position_idx, position] triples to an array.
let array = [];
for (let i = 0; i < paths.length; ++i) {
const path = paths[i];
for (let j = 0; j < path.length; ++j) {
array.push({path_idx: i, position_idx: j, position: path[j]});
}
}
// Sort the array by position values.
array.sort(function(a, b) {
if (a.position < b.position)
return -1;
else if (a.position > b.position)
return 1;
else
return 0;
});
// Drop items that are surrounded by points on the same path, as these
// items will definitely not comprise the optimal pair.
array = array.filter(function(item, idx) {
if (idx === 0 || idx === array.length - 1)
return true;
const left = array[idx - 1];
const right = array[idx + 1];
return item.path_idx !== left.path_idx || item.path_idx !== right.path_idx;
});
// Find the closest items from different paths.
let min_distance = null;
let closest = null;
for (let i = 0; i < array.length; ++i) {
let item_i = array[i];
for (let j = i + 1; j < array.length; ++j) {
let item_j = array[j];
if (item_i.path_idx === item_j.path_idx)
continue;
const distance = item_j.position - item_i.position;
if (min_distance === null || distance < min_distance) {
min_distance = distance;
closest = [item_i, item_j];
}
break;
}
}
// Output (zero-indexed):
// [
// { path_idx: 1, position_idx: 3, position: 39 },
// { path_idx: 3, position_idx: 1, position: 40 }
// ]
console.log(closest);