首页 > 解决方案 > 如何创建点文件

问题描述

我有一个生成随机图 (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

标签: javagraphvizdotdirected-acyclic-graphs

解决方案


像这样的东西应该工作:

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 图像。


推荐阅读