Java: how to represent graphs?

前端 未结 12 1488
感动是毒
感动是毒 2020-12-02 12:17

I\'m implementing some algorithms to teach myself about graphs and how to work with them. What would you recommend is the best way to do that in Java? I was thinking somethi

12条回答
  •  忘掉有多难
    2020-12-02 12:50

    Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.

    public class Node {
        public String name;
        public List connections;
    }
    

    Each connection is directed, has a start and an end, and is weighted.

    public class Edge {
        public Node start;
        public Node end;
        public double weight;
    }
    

    A graph is just your collection of nodes. Instead of List consider Map for fast lookup by name.

    public class Graph {
        List nodes;
    }
    

提交回复
热议问题