public void Toposort () {//only for directed graphs, the basic idea is to find a non-successor node, delete it, and put it to the end of the sorted array, loop in turn. Until there is no node. int Originalvertex = nvertex;while (Nvertex > 0) {int nosucvert = Getnosuccessorvertex ();//Get a No successor if (Nosucvert = = 1) {System.out.println ("graph has circle"); return;} SORTARRAY[NVERTEX-1] = vertexlist[nosucvert];//Copy the node to be deleted to the sorted array Deletevertex (Nosucvert);//Delete no successor nodes}system.out.println ("Toposort:"); for (int i=0;i< Originalvertex; i++) {System.out.print (" " +sortarray[i].vertexname);}}
public int Getnosuccessorvertex () {Boolean Isendvertex = false;for (int i=0; i < Nvertex; i++) {//For each vertex Isendvertex = Fals e;for (int j=0; j< Nvertex; j + +) {//If the node has a fixed line, each column has a 1, indicating that the node has a successor, jumping out of the loop if (adjmatrix[i][j] = 1) {Isendvertex = True;break;}} Forif (!isendvertex) {//If the node has no successor, return the subscript value of the node return I;}} forreturn-1;}
public void Deletevertex (int vertex) {if (vertex >= 0 && vertex < nVertex-1) {//If the vertex value is the last element, it is not necessary to move the array element, Direct nvertex--can be. for (int i=vertex; i< nVertex-1; i++) {//delete the vertex in the vertex object array; vertexlist[i] = vertexlist[i+1];} for (int j=vertex; j< nVertex-1; j + +) {//For the element starting at line vertex+1, one row up, overwriting the vertex line. for (int k = 0;k < nVertex-1; k++) {adjmatrix[j][k] = adjmatrix[j+1][k];}} The for (int m = vertex;m<nvertex-1; m++) {//) moves the element starting from column vertex+1 to pan left one row, overwriting the vertex column. for (int n = 0;n< nVertex-1; n++) {adjmatrix[n][m] = adjmatrix[n][m+1];}}} --nvertex;//vertex count minus one}
Class Graphapp{public static void Main (String args[]) {Graph g = new Graph (9); G.addvertex (' A '); G.addvertex (' B '); G.addvertex (' C '); G.addvertex (' D '); G.addvertex (' E '); G.addvertex (' F '); G.adddiredge (0, 1); G.adddiredge (1, 2); G.adddiredge (1, 4); G.adddiredge (1, 5); G.adddiredge (4, 3); G.toposort ();}}
Output:
Toposort: A B F E D C
Java implementation topology ordering: Based on adjacency matrix, for Directed loop-free graphs