简体   繁体   English

有哪些方法可以代表Java中的加权有向图?

[英]What are some ways I can represent a weighted, directed graph in Java?

I can't use any external libraries, so I'm trying to think of some ways to build the data structure myself. 我不能使用任何外部库,所以我试着想一些自己构建数据结构的方法。 I was thinking maybe something like this: 我想的可能是这样的:

public class Node{
    Set<Edge> adjacent;
    int value;
}

public class Edge{
    Node target;
    int weight;
}

But I'm guessing there's probably a better way to do it. 但我猜这可能是一种更好的方法。

My eventual use for this graph is to run the Bellman Ford algorithm on it, but I obviously need a functioning graph first! 我最终使用这个图是在它上运行Bellman Ford算法,但我显然首先需要一个功能图!

The answer depends a lot on the algorithms that you are planning to apply to your graphs. 答案很大程度上取决于您计划应用于图表的算法。

There are two common ways to represent a graph - an adjacency list and an adjacency matrix . 表示图形有两种常用方法 - 邻接列表邻接矩阵 In your case, and adjacency matrix is a square array of integers representing weights. 在您的情况下,邻接矩阵是表示权重的整数的正方形数组。 Your representation uses an adjacency list. 您的表示使用邻接列表。

There are algorithms that work better on adjacency matrixes (eg Floyd-Warshall algorithm). 有些算法在邻接矩阵上运行得更好(例如Floyd-Warshall算法)。 Other algorithms work better on adjacency lists (eg Dijkstra's algorithm). 其他算法在邻接列表上更好(例如Dijkstra算法)。 If your graph is sparse, using adjacency matrix may be prohibitive. 如果图形稀疏,则使用邻接矩阵可能会令人望而却步。

As usual, you can represent graphs as Adjacency Lists or Adjacency Matrices. 像往常一样,您可以将图表表示为Adjacency Lists或Adjacency Matrices。 The choice really depends on the details of your problem. 选择真的取决于您的问题的细节。

Using an Adjacency Matrix, you could simply have a matrix of integers, representing the weight. 使用邻接矩阵,您可以简单地得到一个整数矩阵,表示权重。

If you decide to have an Adjacency List, you could simply store a list of list of integers (assuming the nodes of your graph are identified by an integer value), similar to what you've done. 如果您决定使用邻接列表,则可以简单地存储整数列表的列表(假设图形的节点由整数值标识),类似于您所做的。

You can use a node as in an unweighted graph, holding a list of nodes to which it is connected,and additionally add the weights associated with the connections as: 您可以将节点用作未加权图形,保存与其连接的节点列表,并另外添加与连接关联的权重:

public class Node{
    int value;
    HashMap<Node,Integer> adjacency;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM