繁体   English   中英

有向图和无向图-Java

[英]Directed graph and undirected graph - Java

我正在实现一些算法,以教自己关于图以及如何使用它们。 您会推荐什么是用Java做到这一点的最佳方法?

我只是想问一下您是否可以使用有向图和加权有向图的简短类定义来提供简短帮助?

我在网上浏览了一下,但我不希望它的实现,而只是类的简短定义。...您认为最好的数据结构是什么? 相邻列表?

对于无向图,我将其定义如下:

public interface Graph { 
  Collection vertices();  // returns a collection of all the 
        //   Vertex objects in the graph 
  Collection edges();  // returns a collection of all the 
     //   Edge objects in the graph 
  Collection incidentEdges(Vertex v); // returns a collection of  
       //   Edges incident to v 
  boolean isAdjacent(Vertex v, Vertex w); // return true if v and     
}                 //   w are adjacent 

public class Vertex { 
  public boolean visited;  // initially false for all vertices 
} 

public class Edge { 
  Vertex v1, v2;     // undirected edge 
  Vertex opposite(Vertex v); // given a vertex return the one 
}          // at the other end of this edge 

这是一个简单的实现(对于许多基本用例来说,这已经足够了):

public class Graph { 
  public List<Node> nodes = new ArrayList<Node>();
}                

public class Node{
  public List<Node> neighbors = new ArrayList<Node>();
 //here you can add stuff like "public boolean visited;", if your algorithm requires it
} 

(这只是一个例子-有很多实现图形结构的方法)。

使用的数据结构取决于代码的目的。列表通常做得很好,但是如果图形是高度连接的(大多数节点都连接到大多数节点),那么列表会很麻烦,并且通常首选某种矩阵。

例如,要使用矩阵,请保留节点向量,然后使用整数的二维向量来引用节点。

同样,对于创建轻量级的类,您不必为节点声明一个类:您可以提供用于添加节点和边的函数,并且可以使用整数来标识此类元素。

如果计划将它们子类化,则拥有Node或Edge类可能比较合适(例如,在制作显示图形的GUI时可能会很有用),但是如果您需要图形用于某些算法,则使用整数识别节点/边会更快,并且更简单。

暂无
暂无

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

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