package com.atguigu.prim;import java.util.Arrays;public class PrimAlgorithm {public static void mainString[] args) {char[] data = new char[]{'A','B','C','D','E','F','G'};int verxs = data.length;int [][]weight=new int[][]{{10000,5,7,10000,10000,10000,2},{5,10000,10000,9,10000,10000,3},{7,10000,10000,10000,8,10000,10000},{10000,9,10000,10000,10000,4,10000},{10000,10000,8,10000,10000,5,4},{10000,10000,10000,4,5,10000,6},{2,3,10000,10000,4,6,10000},};MGraph graph = new MGraphverxs);MinTree minTree = new MinTree);minTree.createGraphgraph, verxs, data, weight);minTree.showGraphgraph);minTree.primgraph, 1);}}
class MinTree {public void createGraphMGraph graph, int verxs, char data[], int[][] weight) {int i, j;fori = 0; i < verxs; i++) {graph.data[i] = data[i];forj = 0; j < verxs; j++) {graph.weight[i][j] = weight[i][j];}}}public void showGraphMGraph graph) {forint[] link: graph.weight) {System.out.printlnArrays.toStringlink));}}public void primMGraph graph, int v) {int visited[] = new int[graph.verxs];
visited[v] = 1;int h1 = -1;int h2 = -1;int minWeight = 10000; forint k = 1; k < graph.verxs; k++) {forint i = 0; i < graph.verxs; i++) {forint j = 0; j< graph.verxs;j++) {ifvisited[i] == 1 && visited[j] == 0 && graph.weight[i][j] < minWeight) {minWeight = graph.weight[i][j];h1 = i;h2 = j;}}}System.out.println"边<" + graph.data[h1] + "," + graph.data[h2] + "> 权值:" + minWeight);visited[h2] = 1;minWeight = 10000;}}
}class MGraph {int verxs; char[] data;int[][] weight; public MGraphint verxs) {this.verxs = verxs;data = new char[verxs];weight = new int[verxs][verxs];}
}