Given a directed graph G, with edges colored either green or purple, and a vertex S in G, I must find an algorithm that finds the shortest path from s to each vertex in G so the path includes at most two purple edges (and green as much as needed).
I thought of BFS on G after removing all the purple edges, and for every vertex that the shortest path is still infinity, do something to try to find it, but I’m kinda stuck, and it takes alot of the running time as well…
Any other suggestions?
Thanks in advance
Duplicate your graph, so you have G1, G2, G3, such in each graph you redirect purple edges as follows: if (u1, v1) is a purple edge in G1, then change it to (u1, v2).
I.e. You have three graphs where each time you take a purple edge it moves you to the next graph, and on G3 there are no more purple edges. That construction builds the purple restriction into the structure, and will then be enforced automatically.
Now you simply find the shortest path from s to all nodes as usual. With the results you have to choose which is shorter between each path from s to u1, u2, u3.
All in all the construction takes linear time, and the new graph size is O(1) times larger than the original, so APSP takes the same time, and the final run to determine which of the three paths found is shortest is also linear.