如何创建一个点文件

时间:2019-01-28 11:09:10

标签: java graphviz dot directed-acyclic-graphs

我有一个生成随机图(DAG)的程序,如何提取输出图并转换为文件点格式,以便在GraphViz中将其可视化?还是有另一种方法? 这是代码(我已经省略了所有依赖项)和一个简单的生成的输出

public class DigraphGenerator {
    private static final class Edge implements Comparable<Edge> {
        private final int v;
        private final int w;

        private Edge(int v, int w) {
            this.v = v;
            this.w = w;
        }

        public int compareTo(Edge that) {
            if (this.v < that.v) return -1;
            if (this.v > that.v) return +1;
            if (this.w < that.w) return -1;
            if (this.w > that.w) return +1;
            return 0;
        }
    }

    private DigraphGenerator() { }

    public static Digraph dag(int V, int E) {
        if (E > (long) V*(V-1) / 2) throw new IllegalArgumentException("Too many edges");
        if (E < 0)                  throw new IllegalArgumentException("Too few edges");
        Digraph G = new Digraph(V);
        SET<Edge> set = new SET<Edge>();
        int[] vertices = new int[V];
        for (int i = 0; i < V; i++)
            vertices[i] = i;
        StdRandom.shuffle(vertices);
        while (G.E() < E) {
            int v = StdRandom.uniform(V);
            int w = StdRandom.uniform(V);
            Edge e = new Edge(v, w);
            if ((v < w) && !set.contains(e)) {
                set.add(e);
                G.addEdge(vertices[v], vertices[w]);
            }
        }
        return G;
    }

    public static void main(String[] args) {
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);

        StdOut.println("DAG");
        StdOut.println(dag(V, E));
        StdOut.println();
    }

}

输出示例:

DAG 12个顶点,10个边 0:2 1 1: 2: 3: 4:8 5:9 6: 7:8 4 8: 9:8 10:5 11:5 6

DAG 12个顶点,10个边 0:8 1:8 2:5 3: 4:5 5: 6:7 9 8 7: 8: 9: 10: 11:5 7 3

1 个答案:

答案 0 :(得分:0)

类似的东西应该可以工作:

void writeDot(Digraph d){
  try(BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("g.dot")))){
    out.write("digraph {"); 
    out.newLine();
    for(Edge e:d.getEdges()){
      out.write(e.v+" -> "+e.w);
      out.newLine();
    }
    out.write("}");
  }
}

或者您可以看看https://github.com/nidi3/graphviz-java,它负责生成点文件并调用graphviz并直接生成png图像。