Given n electric components and m electric wires to connect them where each wire has a length. Find the optimized wire length between the two components.
Input : Source = A
Destination = C
Explanation: There are five different paths from node A to node C i.e., A->B->C, A->B->D->C, A->D->C, A->E->D->C, A->D->B->C. But the path with smallest or optimized length is A->E->D->C with length as 4.
Given n components and m wires constitute an undirected weighted graph. The task is to calculate the optimized length between two components i.e., the minimum length between the two components. The problem is an application of Dijkstra’s algorithm. Since the source is available, the shortest length from the source to all nodes can be calculated using Dijkstra’s algorithm. This will give the shortest possible length between the given node source and all other nodes as an array. Now, the shortest length can be given from the source to destination using this array. Let’s understand this with the help of an example.
Input: Source = A
Destination = D
Explanation: Use Dijkstra’s algorithm to calculate shortest length from source A to all other nodes.
Vertex Distance from source
The shortest length can be found for any component from source A. Final answer will be the shortest length from A to D i.e., 9.
Below is the implementation of the above approach:
Wire froms 3 to 1 with length 4 Path is : 3 4 5 1
Time Complexity: Time Complexity for the above implementation of Dijkstra’s algorithm is O(n^2).
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.