-1

Suppose I have a set of edges in the form (where each tupe (i,j) is a directed edge from node i to node j):

E=[(1, 6), (1, 7), (2, 3), (2, 6), (3, 2), (3, 8), (4, 5), (4, 7), (5, 4), (5, 9), (6, 1), (6, 7), (6, 2), (7, 1), (7, 6), (7, 4), (8, 9), (8, 3), (9, 8), (9, 5)]

and the distance matrix:

C=[2.5, 5.5, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 2.5, 5.0, 2.0, 5.59, 5.0, 2.0, 5.0, 2.0, 5.0, 2.0]

where each element in C (say in the i-th position) corresponds to the distance between the 2 nodes of the corresponding edge in E (at the i-th position).

Now, I will like to find the shortest path that begins at the origin (node 1), which passes through nodes 2 and 4, and then returns to the origin (a cycle). Is there a way to do this with the NetworkX package in Python? Or is there some other way (that is not computationally costly) to do this?

I looked up https://networkx.github.io/documentation/stable/reference/algorithms/shortest_paths.html for functions with relevance to the shortest path, but I am unable to find one that is suitable for my problem.. Some insight into this will be deeply appreciated!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Stoner
  • 846
  • 1
  • 10
  • 30
  • 1
    This definitely sounds off topic for SO. It's more math.stackexchange. – FHTMitchell Aug 20 '18 at 14:59
  • 2
    @FHTMitchell Probably not math.se, maybe SoftwareEngineering. Algorithm questions are (technically) on-topic here, but they don't often get a good reception. Here on SO we're better suited at helping to implement a specific algorithm correctly, than to pull one out of thin air. – PM 2Ring Aug 20 '18 at 15:04
  • @PM2Ring Thanks for the feedback and I'll take note for future questions posted. I'll like to clarify that it will be great if there is already an implementation for this that's easily accessible, and if it isn't I'm fine with that.. I'll just implement it on my own :) – Stoner Aug 20 '18 at 15:50
  • Short path starting at 1 and ending at what node? – Scott Boston Aug 20 '18 at 18:41
  • @ScottBoston Node 1, which is the origin as defined above. – Stoner Aug 21 '18 at 02:05

1 Answers1

1

You can break this down into simpler problems, which I assume exist in networkx.

Let E and V be the number of edges and vertices in your original graph respectively. Let F be the number of vertices that must be in your cycle (3 in your example: nodes 1, 2 and 4). From now on, I'll refer to them as cycle vertices.

Algorithm:

  1. Compute the distance between each cycle vertex. If you use Dijkstra's algorithm, it's O(E + V log V) for each cycle vertex, so O(FE + FV log V) in total.

  2. Solve the travelling salesman problem over the cycle vertices using the edge weights from step 1, which will cost O(F!). There are approximate algorithms with much better time complexity if this becomes a significant bottleneck.

Total cost is O(max(FE, FVlogV, F!)). It is likely that the F! term will dominate.

c2huc2hu
  • 2,447
  • 17
  • 26