实现图形 - Java

时间:2015-11-12 18:44:09

标签: java graph

此程序的目标是在不使用任何库的情况下在JAVA中实现图形。这不是一个家庭作业,只是一些练习。我正在尝试实现一个单向加权图,稍后可以将其作为参数传递给Kruskal或Prim的算法以实现最小生成树。由于我是数据结构的新手,因此我很难想出如何实现图表。邻接矩阵/列表是我想要避免的,我可以采用以下方法:

/**
 * Graph.java: This is the main file.
 */ 
public class Graph {

    public static void main(String[] args)
    {
        Node n1 = new Node("A");
        Node n2 = new Node("B");
        Node n3 = new Node("C");
        Node n4 = new Node("D");
        Node n5 = new Node("E");
        Node n6 = new Node("F");

        Edges e1 = new Edges(n1, n2, 5);
        Edges e2 = new Edges(n1, n3, 3);
        Edges e3 = new Edges(n2, n4, 5);
        Edges e4 = new Edges(n2, n5, 2);
        Edges e5 = new Edges(n3, n6, 7);
    }
}


/**
 * Node.java class used to represent vertices
 */
public class Node {
    private String name;
    public Node(String name)
    {
        this.name = name;
    }
}

/**
 * Edges.java class used to represent edges.
 */
public class Edges {
    private int weight;
    private Node sNode;
    private Node dNode;
    public Edges(Node sNode, Node dNode, int weight)
    {
        this.sNode = sNode;
        this.dNode = dNode;
        this.weight = weight;
    }
}

1 个答案:

答案 0 :(得分:4)

我个人会保持边缘附着在节点上。我意识到它的边数增加了一倍(因为它们在你的情况下是双向的)但是它使得遍历节点的速度要快得多,因为你不必遍历边缘以找到下一步的位置。我意识到你提到你对邻接列表不感兴趣,但在大多数情况下,就性能而言似乎是一种更好的方法,尽管我确定你有理由。所以我无论如何都要发布代码,只是为了其他人。

(没有得到/设置以保持代码简洁)

public class Node {
    private String name;
    private List<Edge> neighbors;

    public Node(String name) {
        this.name = name;
    }

    public void AddUndirectedEdge(Node destination, int weight) {
        neighbors.Add(new Edge(destination, weight));
        destination.neighbors.Add(new Edge(this, weight));
    }

    private static class Edge {
        public Node destination;
        public int weight;

        public Edge(Node destination, int weight) {
            this.destination = destination;
            this.weight = weight;
        }
    }
}