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
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))
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.
- Find if there is a path between two vertices in a directed graph
- Longest Path in a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Count all possible paths between two vertices
- Construct a graph from given degrees of all vertices
- Articulation Points (or Cut Vertices) in a Graph
- Finding in and out degrees of all vertices in a graph
- Minimum number of edges between two vertices of a Graph
- Minimum Operations to make value of all vertices of the tree Zero
- Maximum and minimum isolated vertices in a graph
- Largest subset of Graph vertices with edges of 2 or more colors
- Check whether given degrees of vertices represent a Graph or Tree
- Minimum initial vertices to traverse whole matrix with given conditions
- Find maximum number of edge disjoint paths between two vertices
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method