用Java编辑实现warshall算法_Warshall算法JAVA实现

package graph;

class Vertex {

public char label;

// -------------------------------------------------------------

public Vertex(char lab) // constructor

{

label = lab;

}

} // end class Vertex

// //

/**

* 有向图

*/

public class WarshallGraph {

private final int MAX_VERTS = 5;

private Vertex vertexList[]; // list of vertices

private int adjMat[][]; // adjacency matrix

private int nVerts; // current number of vertices

private char sortedArray[];

// -------------------------------------------------------------

public WarshallGraph() // constructor

{

vertexList = new Vertex[MAX_VERTS];

// adjacency matrix

adjMat = new int[MAX_VERTS][MAX_VERTS];

nVerts = 0;

for (int j = 0; j < MAX_VERTS; j++)

// set adjacency

for (int k = 0; k < MAX_VERTS; k++)

// matrix to 0

adjMat[j][k] = 0;

} // end constructor

// -------------------------------------------------------------

public void addVertex(char lab) {

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

}

// -------------------------------------------------------------

public void addEdge(int start, int end) {

adjMat[start][end] = 1;

}

// -------------------------------------------------------------

public void displayVertex(int v) {

System.out.print(vertexList[v].label);

}

// -------------------------------------------------------------

public void warshall()

{

for (int y = 0; y < MAX_VERTS; y++) { //行

for (int x = 0; x < MAX_VERTS; x++) { //列

if(adjMat[y][x] == 1){ // y -> x

for (int z = 0; z < MAX_VERTS; z++) {

if(adjMat[z][y] == 1 && z != x){ //z -> y找到连接到 y 的节点

adjMat[z][x] = 1; //z -> x

}

}

}

}

}

} // end topo

// -------------------------------------------------------------

public void printGraph(){

for (int i = 0; i < MAX_VERTS; i++) {

for (int j = 0; j < MAX_VERTS; j++) {

System.out.print(adjMat[i][j] + " ");

}

System.out.println();

}

}

// ------------------------------------------------------------

public static void main(String[] args) {

WarshallGraph theGraph = new WarshallGraph();

theGraph.addVertex('A'); // 0

theGraph.addVertex('B'); // 1

theGraph.addVertex('C'); // 2

theGraph.addVertex('D'); // 3

theGraph.addVertex('E'); // 4

//theGraph.addVertex('F'); // 5

//theGraph.addVertex('G'); // 6

//theGraph.addVertex('H'); // 7

theGraph.addEdge(0, 2); // AD

theGraph.addEdge(1, 0); // AE

theGraph.addEdge(1, 4); // AE

theGraph.addEdge(2, 3); // AE

theGraph.addEdge(3, 4); // BE

theGraph.addEdge(4, 2); // CF

//theGraph.addEdge(3, 6); // DG

//theGraph.addEdge(4, 6); // EG

//theGraph.addEdge(5, 7); // FH

//theGraph.addEdge(6, 7); // GH

theGraph.warshall();

theGraph.printGraph();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值