您没有为多边形坐标提供数据结构,因此我假设它们存储在 data.frame 中。
数据
d <- data.frame(from = c(1, 2, 2, 4, 6, 3), to = c(4, 6, 5, 3, 1, 5))
代码
getEdgesOrdered <- function(current, rest, result = list(unlist(current))) {
if (NROW(rest) == 0) {
result
} else {
to <- current$to
wh <- match(to, rest$from)
if (is.na(wh)) {
wh <- match(to, rest$to)
elem <- setNames(rest[wh, c("to", "from")], c("from", "to"))
} else {
elem <- rest[wh, c("from", "to")]
}
Recall(elem, rest[-wh, ], c(result, list(unlist(elem))))
}
}
getEdgesOrdered(d[1,], d[-1,])
说明
该函数获取第一条边并在剩余的data.frame 的from 列中查找to 节点。如果在那里找不到它,它会在to 列中查找它。然后将当前边附加到结果向量,找到的边从data.frame 中删除,它是要查找的新边。当data.frame 中没有剩余行时,算法停止并返回搜索路径。