Determining the most efficient way to connect a network
The 107th Euler Problem aims to calculate the most efficient way to connect a given network. This is definitely a problem that can be solved using graphs, i.e. it’s a typical minimum spanning tree (MST) problem (Prim’s algorithm). Please note that the code below is just a snapshot of the original code. If one wants to check the entire code, please go to my github repository. I started by creating a class to represent the graph. My representation uses an adjacency matrix, however for space-saving purpose I could have used adjacency lists instead.
Then I created a Prim’s class which has a method to calculate the minimum spanning tree of a given graph. The method, named prim, is explained below together with the class:
As one can see, there are a number of global variables: the graph, the starting node, the maximum integer value (explained below) and two arrays - one containing the distances and another containing the parents. These are very important variables for the prim’s method below:
These first lines initialize the helper variables and the arrays which will hold the information regarding the MST. Furthermore, the following code is the responsible for creating the MST and calculate the total saved:
For the scope of this problem, the save variable is important since it is accumulating the total savings during the process of building the MST. Then it was a matter of parsing the input file into a matrix and pass it on to the Prim’s class in order to perform the calculations. The Main class is also available in my github repository.