You did not provide a data structure for you polygon coordinates, so I assume that they are stored in a data.frame
.
Data
d <- data.frame(from = c(1, 2, 2, 4, 6, 3), to = c(4, 6, 5, 3, 1, 5))
Code
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,])
Explanation
The function takes the first edge and looks up the to
node in the from
column in the remaining data.frame
. If it is not found there, it looks it up in the to
column. The current edge is then appended to the result vector, the found edge is removed from the data.frame
and it is the new edge to look up. When there are no rows left in the data.frame
the algorithm stops and returns the search path.