I’m trying to solve the following problem:
There are N planets in our galaxy. You can travel in between different planets, but not every planet is joined to another one through a safe route. Each route has a given length in light years. Your task is to establish bases on a given set of planets T(where 0
The input consists of N(number of planets), R(number of safe routes between planets), R routes in the form triples A B L, where A and B represent the stellar IDs of the planets, and L represents the distance between them in light years, T(number of planets where bases need to be established), followed by T numbers which represent the IDs of the planets where bases need to be established.
You always start with the planet with ID: 0. There may or may not be needed to establish a base on planet 0.
I tried solving the exercise and managed to get a working solution but it is too slow. I used the Floyd Warshall algorithm to get minimum paths in between any two nodes(planets) in a graph. Next I find the closest planet that needs a base to 0, and calculate that path. Then, I add this planet to a list of “visited planets”, and remove it from the list of “target” planets. I repeat this process until the end, but now I try to find the closest planet from the target planets to ANY of my visited planets(since traveling between them is free, I don’t care where I’ve been last). Then, I add the distance, remove it from targets, add it to visited and keep going until I establish every base necessary.
This provides the correct output, but it is too slow.
Any ideas for improvement? Possibly some altered version of Dijkstra’s algorithm?