privatevoidgetEdgeNum(){ int length = vertex.length; for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { //矩阵值等于Integer.MAX_VALUE表示不相邻,等于0是自己到自己 if (matrix[i][j] != Integer.MAX_VALUE) { edgeNum++; } } } }
/** * print matrix */ privatevoidprintMatrix(){ System.out.println("矩阵:"); for (int[] m : matrix) { for (int c : m) { System.out.print(c + " "); } System.out.println(); } }
/** * 获取字符在结点里的位置 * * @param c 字符 * @return 返回-1没该字符,其他位置 */ privateintgetVertexPosition(char c){ for (int i = 0; i < vertex.length; i++) { if (c == vertex[i]) { return i; } }
return -1; }
/** * 输入开始顶点位置 * * @param x 开始顶点位置 */ publicvoidprime(int x){ int num = vertex.length; //邻边权重 int[] weights = newint[num]; //prime最小生成树结果 char[] result = newchar[num]; //result当前索引 int index = 0;
//复制第一个顶点值 result[index] = vertex[x]; index++;
//init weight 找到顶点相邻边的权重赋值weights[i] for (int i = 0; i < num; i++) { weights[i] = matrix[x][i]; } weights[x] = 0;
//循环遍历娶到最短权重值添加到result中 for (int i = 0; i < num; i++) { if (x == i) { continue; }
int minWeight = Integer.MAX_VALUE; int minWeightIndex = 0;
//计算最小生成树的权重 int sum = 0; for (int i = 1; i < index; i++) { int min = Integer.MAX_VALUE;
int n = getVertexPosition(result[i]); //求当前节点到上面其他节点的最小值 for (int j = 0; j < i; j++) { int m = getVertexPosition(result[j]); if (matrix[m][n] < min) { min = matrix[m][n]; } }
sum += min; }
//打印最小生成树 System.out.printf("PRIME(%c):", vertex[x]); for (int i = 0; i < index; i++) { System.out.printf("%c ", result[i]); } System.out.println(); System.out.printf("权重:%d", sum);