图-无权图-最小化生成树

package k_graph.A_Graph.C_MST;
/**
 * 无向图
 * 最小化生成树
 * @author Administrator
 *
 */
public class MSTApp {
public static void main(String[] args) {
Graph theGraph = new Graph();


theGraph.addVertex('A');
theGraph.addVertex('B');
theGraph.addVertex('C');
theGraph.addVertex('D');
theGraph.addVertex('E');
theGraph.addVertex('F');
theGraph.addVertex('G');
theGraph.addVertex('H');
theGraph.addVertex('I');


theGraph.addEdge(0, 1);
theGraph.addEdge(0, 2);
theGraph.addEdge(0, 3);
theGraph.addEdge(1, 4);
theGraph.addEdge(1, 5);
theGraph.addEdge(2, 5);
theGraph.addEdge(2, 6);
theGraph.addEdge(6, 7);
theGraph.addEdge(3, 8);

theGraph.mst();
}
}package k_graph.A_Graph.C_MST;


public class Graph {
private final int MAX_VERTS = 20;
private Vertex vertexList[];
private int adjMat[][];
private int nVerts;
private StackX theStackX;


public Graph() {
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
theStackX = new StackX();


for (int i = 0; i < MAX_VERTS; i++) {
for (int k = 0; k < MAX_VERTS; k++) {
adjMat[i][k] = 0;
}
}
}


public void addVertex(char lab) {


vertexList[nVerts++] = new Vertex(lab);
}


public void addEdge(int start, int end) {


adjMat[start][end] = 1;
adjMat[end][start] = 1;
}


public void displayVertex(int j) {


System.out.print(vertexList[j].label);
}


public void mst() {
vertexList[0].wasVisited = true;
theStackX.push(0);
while (!theStackX.isEmpty()) {
int currentVertex = theStackX.peek();
int v = getAdjUnvisitedVertex(currentVertex);
if (v != -1) {
vertexList[v].wasVisited = true;
theStackX.push(v);


// 输出邻接2顶点的值
displayVertex(currentVertex);
displayVertex(v);
System.out.println();
} else
theStackX.pop();
}
for (int i = 0; i < nVerts; i++) {
vertexList[i].wasVisited = false;
}
}


public int getAdjUnvisitedVertex(int v) {


int i = -1;
for (int j = 0; j < nVerts; j++) {
if (adjMat[v][j] == 1 && vertexList[j].wasVisited == false) {
i = j;
break;
}
}
return i;
}
}package k_graph.A_Graph.C_MST;


public class StackX {
private final int SIZE = 20;
private int[] st;
private int top;


public StackX() {
st = new int[SIZE];
top = -1;
}


public void push(int key) {


st[++top] = key;
}


public int peek() {


return st[top];
}


public int pop() {


return st[top--];


}


public boolean isEmpty() {


return top == -1;
}
}package k_graph.A_Graph.C_MST;


public class Vertex {
public char label;
public boolean wasVisited;


public Vertex(char label) {
this.label = label;
wasVisited = false;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值