Minimal Spanning Tree (Prim) import java.io.*; import java.util.StringTokenizer; /** * MinimalSpanningTree: Determine the minimal spanning tree in a * weighted graph using Prim's method. See Thomas H. Cormen, Charles * E. Leiserson, Ronald R. Rivest: Introduction to Algortithms, * Chapter 24, McGraw-Hill, 1990. * * @author werner.hett@hti.bfh.ch */ public class MinimalSpanningTree { int [][] minimalTree; int n; int total; // weight matrix of the resulting tree // number of nodes // total weight of the result static final int WHITE = 0; static final int GREEN = 1; static final int RED = 2; // nodes in set V3 are WHITE // nodes in set V2 are GREEN // nodes in set V1 are RED /** * Construct the minimal spanning tree of a graph given by its weight * matrix. Positive entries denote weight (or cost or distance) of * the corresponding edge; zero entries represent "no edge". */ MinimalSpanningTree (int [][] weight) { n = weight.length; minimalTree = new int [n][n]; int [] parent = new int [n]; int [] color = new int [n]; int [] dist = new int [n]; int x = 0; color [x] = RED; // number of nodes // all filled with 0 // for any green node x, parent[x] //is the closest red node. // color of the nodes (initially WHITE) // distance from parent node // x is the node that most recently became RED for (int count = 1; count < n; count++) { // Process the newly RED node x. for (int y = 0; y < n; y++) if (weight [x][y] > 0) { // y int newDist = weight [x][y]; if (color [y] == WHITE) { // y color [y] = GREEN; parent [y] = x; dist [y] = newDist; } else if (color [y] == GREEN && parent [y] = x; // y dist [y] = newDist; } } is a neighbor of x becomes GREEN newDist < dist [y]) { gets a new parent // Find the GREEN node with the smallest distance value. // It becomes the new x. boolean firstFound = false; for (int z = 0; z < n; z++) { if (color [z] == GREEN) if (! firstFound) { firstFound = true; x = z; } else if (dist [z] < dist [x]) x = z; } if (! firstFound) throw new RuntimeException ("MinimalSpanningTree: graph is not connected"); color [x] = RED; minimalTree [x][parent[x]] = dist[x]; minimalTree [parent[x]][x] = dist[x]; // uncomment the following to see the progress of the algorithm System.out.println (parent[x] + " - " + x + " (" + dist[x] + ")"); } // calculate the total weight for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) total += minimalTree [i][j]; } /** * Construct a simple string representation of the minimal * spanning tree */ public String toString() { String text = "MinimalSpanningTree [total = " + total + ":\n"; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) { int w = minimalTree [i][j]; if (w > 0) text += i + " - " + j + " (" + w + ")\n"; } text += "]"; return text; } /** * A main program used to test the algorithm. The test graph is * read from a file which has the following format: * * <number of nodes> <new-line> * {<fromNode> <toNode> <weight> <new-line>} */ public static void main (String [] args) { // see skeleton ..... } }