java数据结构和算法------图(最小生成树Prim)

时间:2021-05-17 11:35:59
 1 package iYou.neugle.graph;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 //创建图过程的代码在图的那篇博文中,此处直接使用
7 public class Prim {
8 private MyGraph1 graph;
9 private List<Integer> v = new ArrayList<Integer>();// 待处理集合
10 private List<Integer> u = new ArrayList<Integer>();// 已处理集合
11
12 public Prim(MyGraph1 graph) {
13 this.graph = graph;
14 }
15
16 private void Init() {
17 for (int i = 0; i < this.graph.getGraph().maxNum; i++) {
18 v.add(i);
19 }
20 }
21
22 // Prim核心方法
23 public void PrimCore() {
24 this.Init();
25 u.add(v.get(0));
26 v.remove(0);
27 System.out.println("最小生成树为--------");
28 int weight = 0;
29 while (u.size() < this.graph.getGraph().maxNum) {
30 int minw = Integer.MAX_VALUE;
31 int v1 = 0, v2 = 0, r = 0;
32 for (int i = 0; i < this.u.size(); i++) {
33 int a = this.u.get(i);
34 for (int j = 0; j < this.v.size(); j++) {
35 int b = this.v.get(j);
36 int currentw = this.graph.getGraph().edge[a][b];
37 if (currentw > 0 && currentw < minw) {
38 minw = currentw;// 权值
39 v1 = a;// 第一条边
40 v2 = b;// 第二条边
41 r = j;// 在v中待删除元素
42 }
43 }
44 }
45 System.out.println((v1 + 1) + "->" + (v2 + 1));
46 weight += minw;
47 this.u.add(v2);
48 this.v.remove(r);
49 }
50 System.out.println("----------------");
51 System.out.println("最小生成树的权值为: " + weight);
52 }
53
54 //主函数
55 public static void main(String[] args) {
56 MyGraph1 graph = new MyGraph1(5, 0);
57 graph.CreateMaxtrixGraph(1, 2, 2);
58 graph.CreateMaxtrixGraph(1, 3, 5);
59 graph.CreateMaxtrixGraph(1, 5, 3);
60 graph.CreateMaxtrixGraph(2, 4, 4);
61 graph.CreateMaxtrixGraph(3, 5, 5);
62 graph.CreateMaxtrixGraph(4, 5, 2);
63 graph.OutPutMaxtrixGraph();
64 Prim prim = new Prim(graph);
65 prim.PrimCore();
66 }
67 }
  1 2 3 4 5 
1 0 2 5 0 3
2 2 0 0 4 0
3 5 0 0 0 5
4 0 4 0 0 2
5 3 0 5 2 0
最小生成树为--------
1->2
1->5
5->4
1->3
----------------
最小生成树的权值为: 12