1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import java.util.ArrayList; import java.util.Arrays; import java.util.List;
public class Prim {
final static int INF = Integer.MAX_VALUE;
public static int[] prim(int[][] matrix) { List<Integer> reachedVertextList = new ArrayList<>();
reachedVertextList.add(0);
int[] parents = new int[matrix.length]; parents[0] = -1;
int weight; int fromIndex = 0; int toIndex = 0;
while (reachedVertextList.size() < matrix.length) { weight = INF;
for (Integer vertexIndex : reachedVertextList) { for (int i = 0; i < matrix.length; i++) { if (!reachedVertextList.contains(i)) { if (matrix[vertexIndex][i] < weight) { fromIndex = vertexIndex; toIndex = i; weight = matrix[vertexIndex][i]; } } } } reachedVertextList.add(toIndex); parents[toIndex] = fromIndex; }
return parents; }
public static void main(String[] args) { int[][] matrix = new int[][]{ {0, 4, 3, INF, INF}, {4, 0, 8, 7, INF}, {3, 8, 0, INF, 1}, {INF, 7, INF, 0, 9}, {INF, INF, 1, 9, 0}, };
int[] parents = prim(matrix); System.out.println(Arrays.toString(parents)); } }
|