package coding;
import java.util.Scanner;
/*
* 最小生成树求解城市间的最短距离
*/
class GraphMatrix1{
static final int MaxNum=20;
char[] Vertex=new char[MaxNum];
int GType;
int VertexNum;
int EdgeNum;
int [][] EdgeWeight=new int [MaxNum][MaxNum];
int [] isTra=new int[MaxNum];
}
public class cha07_minTree {
static final int MaxValue=65535;
static final int USED=0;
static final int Nol=-1;
static Scanner input =new Scanner(System.in);
static void CreateGraph(GraphMatrix1 GM){
int i,j,k;
int weight;
char EstartV,EendV;
System.out.printf("输入图中各顶点的信息:\n");
for(i=0;i<GM.VertexNum;i++){
System.out.printf("第%d个顶点:",i+1);
GM.Vertex[i]=(input.next().toCharArray()[0]);
}
System.out.printf("输入构成各边的顶点及权值:\n");
for(k=0;k<GM.EdgeNum;k++){
System.out.printf("第%d条边:",k+1);
EstartV=input.next().charAt(0);
EendV=input.next().charAt(0);
weight=input.nextInt();
for(i=0;EstartV!=GM.Vertex[i];i++);
for(j=0;EendV!=GM.Vertex[j];j++);
GM.EdgeWeight[i][j]=weight;
if(GM.GType==0){
GM.EdgeWeight[i][j]=weight;
}
}
}
static void clearGraph(GraphMatrix1 GM){
int i,j;
for(i=0;i<GM.VertexNum;i++){
for(j=0;j<GM.VertexNum;j++){
GM.EdgeWeight[i][j]=MaxValue;
}
}
}
static void OutGraph(GraphMatrix1 GM){
int i,j;
for(j=0;j<GM.VertexNum;j++){
System.out.printf("\t%c",GM.Vertex[j]);
}
System.out.println();
for(i=0;i<GM.VertexNum;i++){
System.out.printf("%c",GM.Vertex[i]);
for(j=0;j<GM.VertexNum;j++){
if(GM.EdgeWeight[i][j]==MaxValue){
System.out.printf("\tZ");
}
else{
System.out.printf("\t%d",GM.EdgeWeight[i][j]);
}
}
System.out.println();
}
}
static void primGraph(GraphMatrix1 GM){
int i,j,k,min,sum;
int[]weight=new int[GraphMatrix1.MaxNum];
char[]vtempx=new char[GraphMatrix1.MaxNum];
sum=0;
for(i=1;i<GM.VertexNum;i++){
weight[i]=GM.EdgeWeight[0][i];
if(weight[i]==MaxValue){
vtempx[i]=(char)Nol;
}else{
vtempx[i]=GM.Vertex[0];
}
}
vtempx[0]=USED;
weight[0]=MaxValue;
for(i=1;i<GM.VertexNum;i++){
min=weight[0];
k=i;
for(j=0;j<GM.VertexNum;j++){
if(weight[j]<min&&vtempx[j]>0){
min=weight[j];
k=j;
}
}
sum+=min;
System.out.printf("(%c,%c),",vtempx[k],GM.Vertex[k]);
vtempx[k]=USED;
weight[k]=MaxValue;
for(j=0;j<GM.VertexNum;j++){
if(GM.EdgeWeight[k][j]<weight[j]&&vtempx[j]!=0){
weight[j]=GM.EdgeWeight[k][j];
vtempx[j]=GM.Vertex[k];
}
}
}
System.out.println("最小生成树的总权值:"+sum);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
GraphMatrix1 GM=new GraphMatrix1();
char again;
String go;
System.out.println("需找最小生成树");
do{
System.out.printf("请输入生成图的类型 :\n");
GM.GType=input.nextInt();
System.out.printf("输入图的顶点数量:\n");
GM.VertexNum=input.nextInt();
System.out.printf("输入图的边数量:\n");
GM.EdgeNum=input.nextInt();
clearGraph(GM);
CreateGraph(GM);
System.out.println("最小生成树的边为:");
primGraph(GM);
System.out.println("继续玩吗?(y/n)");
go=input.next();
}while(go.equalsIgnoreCase("y"));
System.out.println("游戏结束!");
}
}
最小生成树(城市之间的最短距离)
最新推荐文章于 2019-08-06 12:49:57 发布