1

I'm trying to implement Dijkstra's algorithm for finding the shortest path with a node constraint in Matlab. Specifically, I want to force the path to go through a given set of nodes.

I have an adjacency matrix as input and I need the function to take a start node, end node, and constraint as an array. The algorithm should also be able to handle multiple constraints and execute quickly.

Exemple for a graph

Here the shortest path between A and E is 7 A⇒B⇒E, But i want to get the shortest path between A and E going through C. Ideadly i want an algorithm that can find the shortest path between two nodes and going through one or more nodes.

Can anyone provide an explanation of how to modify Dijkstra's algorithm to handle these constraints and help me with the implementation in Matlab?

Thank you!

  • There are numerous answers for this question on Stack Overflow in other languages (like [this one](https://stackoverflow.com/questions/25368709/dijkstras-algorithm-with-must-pass-nodes)), and the approach here is the same. Given a set S of nodes which contains the start and end nodes, and all nodes that must be visited, find the shortest path between all pairs of nodes in S. Create a new graph using the the nodes in S and the calculated distances. Now solve [TSP](https://en.wikipedia.org/wiki/Travelling_salesman_problem) on the new graph. – beaker May 08 '23 at 03:37
  • Did my answer help you? @abdoessordo – S H Jun 10 '23 at 11:14

1 Answers1

1

Since the path needs to go through C, find the shortest path between A and C, and then the shortest path between C and B, then combine them.
You can do that with any number of constraints by checking all the possibilities of the order in which you go through the nodes, which will take at least O(n!) for n constraints.
For a more general solution with any number of nodes as a constraint, create a new graph only with A,B and those nodes, then use an algorithm that visits all nodes in a graph.
More information about it here.

S H
  • 415
  • 3
  • 14