evenfurther / pathfinding

Pathfinding library for rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

yen returns paths with the same cost for big graphs

TiagoCavalcante opened this issue · comments

Here is a part of a test program that uses the yen function:

let path = yen(
  &start,
  |&vertex| {
    graph
      .get_neighbors(vertex)
      .iter()
      .map(|&neighbor| (neighbor, 1))
      .collect::<Vec<_>>()
  },
  |&vertex| vertex == end,
  10,
);

println!("{:?}", path);

And its output:

[([0, 77, 10], 2), ([0, 5, 49, 10], 3), ([0, 6, 97, 10], 3), ([0, 9, 90, 10], 3), ([0, 66, 83, 10], 3), ([0, 15, 77, 10], 3), ([0, 66, 35, 10], 3), ([0, 16, 90, 10], 3), ([0, 32, 2, 10], 3), ([0, 16, 35, 10], 3)]

The k-th shortest path is the k-th element of a sorted list of paths with DIFFERENT costs that start in the shortest path.

The full program can be found here.

An implementation of the Yen's algorthm can be found on Wikipedia.

Hi Tiago. Thanks for your report. I do not agree that paths must have different costs and I would need some convincing to revert this position.

The k-th shortest path is the k-th element of a sorted list of paths with DIFFERENT costs that start in the shortest path.

Where do you see that stated? That seems counterintuitive as Yen's algorithm is often used to find alternatives in routing. Having one or more alternatives with the same cost is beneficial.

An implementation of the Yen's algorthm can be found on Wikipedia.

Indeed. If you look at the pseudo-code, you'll see that it tries to find a minimal-length different path once the identical root paths have been removed and adds that to set B. Then an element of set B with minimal cost is added to set A; other elements of set B with identical cost are not removed and will be used for filling A in subsequent rounds. This is even noted as a possible improvement in the Wikipedia page ("Also, if container B has K-k paths of minimum length, in reference to those in container A, then they can be extract and inserted into container A since no shorter paths will be found"). Since A is what will be returned by the algorithm, it shows that returning paths with identical costs is definitely possible (and desired).

What can be confusing here is that in Wikipedia example they only ask for the 3 shortest paths. However, those have different costs because there is no way to find a second path with cost 5 or a second path with cost 7. Should they have asked for the 4 shortest paths, they would have received two paths with cost 8 (e.g., A³ = [C, D, F, H] and A⁴ = [C, E, F, G, H]).

What do you think?

Well, that makes sense.

Also, thanks for the comments in your code, they are really helpful!