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();
}
}