Exemple #1
0
  static <Vertex extends BaseVertex, Edge extends BaseEdge<Vertex>> Vector<Edge> convertToDag(
      BaseGraph<Vertex, Edge> graph) {
    System.out.println("start convertToDag");
    System.out.println(graph.getEdgesCount());
    // copied from Dag.finACycle
    byte[] mark = new byte[graph.getVerticesCount()];
    BaseVertex[] V = graph.getVertexArray();
    BaseVertex[] parent = new BaseVertex[mark.length];
    BaseVertex[] root = new BaseVertex[mark.length];
    Integer[] height = new Integer[mark.length];
    LibraryUtils.falsifyVertexMarks(graph);

    // start from one vertex and go to it's neighbors [BFS], continue until
    // you meet a MARKed vertex
    HashSet<Vertex> visitedVertices = new HashSet<Vertex>();
    LinkedList<Vertex> bfsStack = new LinkedList<Vertex>();
    Vertex cycleStart = null;
    Vertex cycleEnd = null;

    // visitedVertices.add(current);
    int scan = 0;
    int counter = 0;
    Vertex current;
    // perform a nonrecursive dfs
    for (scan = 0; scan < V.length; scan++) {
      Vertex u = (Vertex) V[scan];
      if (!u.getMark()) {
          /* Start a new search from u */
        bfsStack.addFirst(u);
        root[u.getId()] = u;
        height[u.getId()] = 0;
        while (!bfsStack.isEmpty()) {
          Vertex v = bfsStack.removeFirst();
          if (!v.getMark()) {
            v.setMark(true);
            counter++;
            for (Vertex w : graph.getNeighbors(v))
              if (!w.getMark()) {
                bfsStack.push(w);
                parent[w.getId()] = v;
                root[w.getId()] = u;
                height[w.getId()] = height[v.getId()] + 1;
              }
          }
        }
      }
    }

    Vector<Edge> ret = new Vector<Edge>();
    // try to find backedges
    for (Edge e : graph.edges()) {
      int src = e.source.getId();
      int trg = e.target.getId();
      if (root[src] == root[trg] && height[src] > height[trg]) {
        ret.add(e);
        System.out.println(ret.size());
        // cycleStart = e.target;
        // cycleEnd = e.source;
        //
        //
        // current = cycleEnd;
        // LinkedList<Vertex> ret = new LinkedList<Vertex>();
        // ret.addFirst(current);
        // while (current != null && current != cycleStart) {
        // current = (Vertex) parent[current.getId()];
        // ret.addFirst(current);
        // }
        // if (current != null)
        // return;

      }
    }
    return ret;
  }