We are given a map of cities connected with each other via cable lines such that there is no cycle between any two cities. We need to find the maximum length of cable between any two cities for given city map.
Input : n = 6 1 2 3 // Cable length from 1 to 2 (or 2 to 1) is 3 2 3 4 2 6 2 6 4 6 6 5 5 Output: maximum length of cable = 12
Method 1 (Simple DFS)
We create undirected graph for given city map and do DFS from every city to find maximum length of cable. While traversing, we look for total cable length to reach the current city and if it’s adjacent city is not visited then call DFS for it but if all adjacent cities are visited for current node, then update the value of max_length if previous value of max_length is less than current value of total cable length.
Maximum length of cable = 12
Time Complexity : O(V * (V + E))
Method 2 (Efficient : Works only if Graph is Directed)
We can solve above problem in O(V+E) time if the given graph is directed instead of undirected graph. Below are steps.
1) Create a distance array dist and initialize all entries of it as minus infinite
2) Order all vertices in toplogical order.
3) Do following for every vertex u in topological order.
…..Do following for every adjacent vertex v of u
………..if (dist[v] < dist[u] + weight(u, v))
……………dist[v] = dist[u] + weight(u, v)
4) Return maximum value from dist
Since there is no negative weight, processing vertices in topological order would always produce an array of longest paths dist such that dist[u] indicates longest path ending at vertex ‘u’.
The implementation of above approach can be easily adopted from here. The differences here are, there are no negative weight edges and we need overall longest path (not longest paths from a source vertex). Finally we return maximum of all values in dist.
Time Complexity : O(V + E)
This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team GeeksForGeeks. If you have any better approach for this problem then please share.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.