原理
视频讲解:
169_尚硅谷_Prim算法解决修路问题思路图解_哔哩哔哩_bilibili
S是已经在生成树, V-S是未在生成树。
代码
根据尚硅谷算法代码修改
public class Prim {
public static void main(String[] args) {
//测试看看图是否创建ok
char[] data = new char[]{'A','B','C','D','E','F','G'};
int verxs = data.length;
//邻接矩阵的关系使用二维数组表示,10000这个大数,表示两个点不联通
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},};
Graph minTree = new Graph(data,weight);
minTree.prim( 1);//
}
}
class Graph {
private char[] vertex; // 顶点数组
private int[][] matrix; // 邻接矩阵
private int[] visited; // 标记结点(顶点)是否被访问过
public Graph(char vertex[], int[][] matrix) {
this.vertex = vertex;
this.matrix = matrix;
visited=new int[vertex.length];
}
//编写prim算法,得到最小生成树
/**
* @param v 表示从图的第几个顶点开始生成'A'->0 'B'->1...
*/
public void prim(int v) {
visited[v] = 1;
//h1 和 h2 记录两个顶点的下标
int h1 = -1;
int h2 = -1;
int minWeight = 10000; //将 minWeight 初始成一个大数,后面在遍历过程中,会被替换
for(int k = 1; k < vertex.length; k++) {//因为有 vertex.length 个顶点,普利姆算法结束后,有 vertex.length-1个边
//这个是确定每一次生成的子图 ,和哪个结点的距离最近
for(int i = 0; i < vertex.length; i++) {// i结点表示被访问过的结点
for(int j = 0; j< vertex.length;j++) {//j结点表示还没有访问过的结点
if(visited[i] == 1 && visited[j] == 0 && matrix[i][j] < minWeight) {
//替换minWeight(寻找已经访问过的结点和未访问过的结点间的权值最小的边)
minWeight = matrix[i][j];
h1 = i;
h2 = j;
}
}
}
//找到一条边是最小
System.out.println("边<" + vertex[h1] + "," + vertex[h2] + "> 权值:" + minWeight);
//将当前这个结点标记为已经访问
visited[h2] = 1;
//minWeight 重新设置为最大值 10000
minWeight = 10000;
}
}
}