将10条边,连接即可,但是总的里程数不是最小
正确|的思路,就是尽可能的选择少的路线,并且每条路线最小,保证总里程数最少
修路问题本质就是就是最小生成树问题,先介绍一下最小生成树(Minimum Cost Spanning Tree),简称MST:
给定一个带权的无向连通图,如何选取一棵生成树,使树上所有边上权的总和为最小,这叫最小生成树:
package ShangGuiGu.Algorithm.Prim;
import java.util.Arrays;
/**
* 普利姆算法
*/
public class PrimAlgorithm {
public static void main(String[] args) {
//结点代表七个村庄
char[] data={
'A','B','C','D','E','F','G'};
//结点之间的权 10000定义代表无穷大,其它为正常距离
int[][] weight={
{
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}
};
int verxs=data.length;
//创建MGraph对象
MGraph graph = new MGraph(verxs);
//创建最小二叉树
MinTree minTree = new MinTree();
minTree.createGraph(graph,data,weight);
//打印graph
// minTree.showGraph(graph);
//以0(A)结点为顶点,开始构建最小生成树 0->A, 1->B, 2->C, 3->D, 4->E, 5->F, 6->G
minTree.prim(graph,6);
}
}
class MinTree{
/**
* 创建图
* @param graph 初始图
* @param data 图中的结点
* @param weight 图的边(权)
*/
public void createGraph(MGraph graph,char[] data,int[][] weight){
for (int i = 0; i < graph.verxs; i++) {
graph.data[i]=data[i];
for (int j = 0; j < graph.verxs; j++) {
graph.weight[i][j]=weight[i][j];
}
}
}
/**
* 显示图的邻接矩阵
* @param graph
*/
public void showGraph(MGraph graph){
for (int[] link:graph.weight){
System.out.println(Arrays.toString(link));
}
}
/**
* 编写普利姆算法,得到最小生成树
* @param graph
* @param start 顶点(开始的结点)
*/
public void prim(MGraph graph,int start){
//标记结点是否被访问过,0未被访问,1被访问 数组元素初始都为0
int[] visitedPoint = new int[graph.verxs];
//从start结点开始(顶点),所以标记为访问过
visitedPoint[start]=1;
int minWeight=10000;
//每次找到已访问顶点间与未访问顶点间的最短距离时,记录当前的已访问结点pointA和未访问结点pointB,初始-1
int pointA=-1;
int pointB=-1;
//k从1到graph.verxs,所遍历的次数为 结点数-1,即最小生成树的边
for (int k = 1; k <graph.verxs; k++) {
for (int i = 0; i < graph.verxs; i++) {
//这一层可以看作是遍历已访问的结点
for (int j = 0; j < graph.verxs; j++) {
//这一层可以看作是遍历未访问的结点
if (visitedPoint[i]==1&visitedPoint[j]==0&graph.weight[i][j]<minWeight){
//更新已访问顶点间与未访问顶点间的最短距离
minWeight=graph.weight[i][j];
pointA=i;
pointB=j;
}
}
}
//每次i,j循环完,相当于从已访问结点间与未访问结点间,找到了最短的距离,并且将找到的那个结点标记为已访问
visitedPoint[pointB]=1;
//打印每次找到的最短距离(两结点间)graph.weight[pointA][pointB]
System.out.println("<"+graph.data[pointA]+graph.data[pointB]+">:"+graph.weight[pointA][pointB]);
//更新minWeight进行下一次k循环,再次找已访问结点间与未访问结点间的最短距离
minWeight=10000;
}
}
}
class MGraph{
int verxs;
char data[];
int weight[][];
public MGraph(int verxs){
this.verxs=verxs;
this.data=new char[verxs];
this.weight=new int[verxs][verxs];
}
}