示例#1
0
  private static List<Integer> doTopologicalSort(Graph<Coordinate, Street> g) {
    final GraphHandler<Coordinate, Street> handler = new GraphHandler<Coordinate, Street>(g, true);

    GraphSearchProcessor gsp =
        new GraphSearchProcessor<Coordinate, Street>() {
          Stack<Integer> stack = new Stack();
          boolean foundCycle = false;

          @Override
          public void processVertexEarly(Graph<Coordinate, Street> graph, int vID) {}

          @Override
          public void processEdge(
              Graph<Coordinate, Street> graph, int eID, int vIDfrom, int vIDto) {
            if (handler.getVertexState(vIDto) == GraphHandler.DiscoverState.DISCOVERED) {
              // We have found a cycle and need to abort!
              handler.stopSearch();
              foundCycle = true;
            }
          }

          @Override
          public void processVertexLate(Graph<Coordinate, Street> graph, int vID) {
            stack.push(vID);
          }

          @Override
          public Object getResults() {
            ArrayList<Integer> topSortOrder = new ArrayList<Integer>();
            if (foundCycle) return topSortOrder;

            while (!stack.isEmpty()) topSortOrder.add(stack.pop());

            return topSortOrder;
          }
        };

    handler.addGraphSearchProcessor(gsp);
    handler.doExhaustiveDFS();
    ArrayList<Integer> ret = (ArrayList<Integer>) gsp.getResults();

    return ret;
  }