1.主要思想
Prim算法,从图的某一个顶点开始,找到权值最小的顶点,依次遍历,最后生成一个最小生成树
2.图示
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200809132444220.PNG)
3.代码实现
1.图
package prim;
public class Graph {
int vertex;
char[] value;
int[][] weight;
public Graph() {
}
public Graph(int vertex) {
this.vertex = vertex;
value = new char[vertex];
weight = new int[vertex][vertex];
}
}
2.最小生成树
package prim;
import jdk.dynalink.NamedOperation;
import java.util.Arrays;
public class MinTree {
public void CreatGraph(Graph graph, int vertex, char[] value, int[][] weight) {
for (int i = 0; i < vertex; i++) {
for (int j = 0; j < vertex; j++) {
graph.value[i] = value[i];
graph.weight[i][j] = weight[i][j];
}
}
}
public void ShowGraph(Graph graph) {
for (int[] arr : graph.weight) {
System.out.print(Arrays.toString(arr));
System.out.println();
}
}
public void Prim(Graph graph, int vertex) {
int[] visited = new int[graph.vertex];
visited[vertex] = 1;
int v1 = -1, v2 = -1;
int MaxValue = Integer.MAX_VALUE;
for (int edge = 1; edge < graph.vertex; edge++) {
for (int isVisit = 0; isVisit < graph.vertex; isVisit++) {
for (int NoVisited = 0; NoVisited < graph.vertex; NoVisited++) {
if (visited[isVisit] == 1 && visited[NoVisited] == 0 && graph.weight[isVisit][NoVisited] < MaxValue) {
MaxValue = graph.weight[isVisit][NoVisited];
v1 = isVisit;
v2 = NoVisited;
}
}
}
System.out.println("<" + graph.value[v1] + "," + graph.value[v2] + ">" + "权值:" + MaxValue);
visited[v2] = 1;
MaxValue = Integer.MAX_VALUE;
}
}
}
3.入口
package prim;
public class Input {
public static void main(String[] args) {
char[] value = {'A', 'B', 'C', 'D'};
int infinity = Integer.MAX_VALUE;
int[][] weight = {
{infinity, 100, 20, infinity},
{100, infinity, 70, 60},
{20, 70, infinity, 50},
{infinity, 60, 50, infinity}
};
Graph graph = new Graph(value.length);
MinTree minTree = new MinTree();
minTree.CreatGraph(graph, value.length, value, weight);
minTree.ShowGraph(graph);
minTree.Prim(graph, 0);
}
}