// topo.java // demonstrates topological sorting // to run this program: C>java TopoApp //////////////////////////////////////////////////////////////// class Vertex { public char label; // label (e.g. 'A') // ------------------------------------------------------------- public Vertex(char lab) // constructor { label = lab; } } // end class Vertex //////////////////////////////////////////////////////////////// class Graph { private final int MAX_VERTS = 20; private Vertex vertexList[]; // list of vertices private int adjMat[][]; // adjacency matrix private int nVerts; // current number of vertices private char sortedArray[]; // ------------------------------------------------------------- public Graph() // constructor { vertexList = new Vertex[MAX_VERTS]; // adjacency matrix adjMat = new int[MAX_VERTS][MAX_VERTS]; nVerts = 0; for(int j=0; j 0) // while vertices remain, { // get a vertex with no successors, or -1 int currentVertex = noSuccessors(); if(currentVertex == -1) // must be a cycle { System.out.println("ERROR: Graph has cycles"); return; } // insert vertex label in sorted array (start at end) sortedArray[nVerts-1] = vertexList[currentVertex].label; deleteVertex(currentVertex); // delete vertex } // end while // vertices all gone; display sortedArray System.out.print("Topologically sorted order: "); for(int j=0; j 0 ) // if edge to { // another, isEdge = true; break; // this vertex } // has a successor } // try another if( !isEdge ) // if no edges, return row; // has no successors } return -1; // no such vertex } // end noSuccessors() // ------------------------------------------------------------- public void deleteVertex(int delVert) { if(delVert != nVerts-1) // if not last vertex, { // delete from vertexList for(int j=delVert; j