I have a parser from my raw input to a petgraph::UnGraph structure. I need to find the shortest path that visits all nodes. I found algo::dijkstra, but from what I understood, Dijkstra would only give me the shortest path connecting two specific nodes.
Is there a function in the petgraph library that offers a way to solve the travelling salesman problem easily, or will I need to implement a solver myself? I browsed the documentation, but couldn't find anything, but maybe it's just my limited experience with graph algorithms.
I've been playing with petgraph for a little while and took your question as a challenge. I find petgraph very powerful, but like many complex systems it is hard to understand and the documentation doesn't give enough examples.
For example what is the diffence between an
EdgeReferenceand anEdgeIndex?If I have an
EdgeReferencehow do I get anEdgeIndex?If have an
EdgeIndexhow do I get theNodeIndexs it connects?Anyway I created a crude TSP solver using petgraph as a starting point for you. Please note that it is minimally tested,
ni_to_nis unneeded, but I left it in case it is useful to you, and many improvements are crying out to be made. But, it should give you some idea how you might take anUngraph<String, u32>(nodes are city names and edge weights are u32 distances) and get to an approximate TSP solution.My basic strategy is to use petgraph's
min_spanning_tree()then to create a cycle.See the comments below for more.
I hope this is useful, if you improve it, please post!