《算法导论》从22章开始图算法。但是Java JDK中没有Graph相关的库,自己实现的话可维护性较差。
JGraphT是一个开源的图理论数据结构和算法的开源库。可以在学习《算法导论》的同时学习该库,同时可以基于该库实现《算法导论》中相关图算法。
JGraphT主页
JGraphT 源码GitHub主页
JGraphT jar包GitHub主页
JGraphT实现细节
将“JGraphT jar包GitHub主页”的lib文件夹下的jgrapht-core-0.9.2.jar包添加项目工程中。
第一个实例时官方提供的简单有向图和无向图的例子。
import java.net.*;
import org.jgrapht.*;
import org.jgrapht.graph.*;
/**
* A simple introduction to using JGraphT.
*
* @author Barak Naveh
* @since Jul 27, 2003
*/
public final class HelloJGraphT
{
private HelloJGraphT()
{
} // ensure non-instantiability.
/**
* The starting point for the demo.
*
* @param args ignored.
*/
public static void main(String [] args)
{
UndirectedGraph<String, DefaultEdge> stringGraph = createStringGraph();
// note undirected edges are printed as: {<v1>,<v2>}
System.out.println(stringGraph);
// create a graph based on URL objects
DirectedGraph<URL, DefaultEdge> hrefGraph = createHrefGraph();
// note directed edges are printed as: (<v1>,<v2>)
System.out.println(hrefGraph);
}
/**
* Creates a toy directed graph based on URL objects that represents link
* structure.
*
* @return a graph based on URL objects.
*/
private static DirectedGraph<URL, DefaultEdge> createHrefGraph()
{
DirectedGraph<URL, DefaultEdge> g =
new DefaultDirectedGraph<>(DefaultEdge.class);
try {
URL amazon = new URL("http://www.amazon.com");
URL yahoo = new URL("http://www.yahoo.com");
URL ebay = new URL("http://www.ebay.com");
// add the vertices
g.addVertex(amazon);
g.addVertex(yahoo);
g.addVertex(ebay);
// add edges to create linking structure
g.addEdge(yahoo, amazon);
g.addEdge(yahoo, ebay);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return g;
}
/**
* Create a toy graph based on String objects.
*
* @return a graph based on String objects.
*/
private static UndirectedGraph<String, DefaultEdge> createStringGraph()
{
UndirectedGraph<String, DefaultEdge> g =
new SimpleGraph<>(DefaultEdge.class);
String v1 = "v1";
String v2 = "v2";
String v3 = "v3";
String v4 = "v4";
// add the vertices
g.addVertex(v1);
g.addVertex(v2);
g.addVertex(v3);
g.addVertex(v4);
// add edges to create a circuit
g.addEdge(v1, v2);
g.addEdge(v2, v3);
g.addEdge(v3, v4);
g.addEdge(v4, v1);
return g;
}
}
输出:
([v1, v2, v3, v4], [{v1,v2}, {v2,v3}, {v3,v4}, {v4,v1}])
([http://www.amazon.com, http://www.yahoo.com, http://www.ebay.com], [(http://www.yahoo.com,http://www.amazon.com), (http://www.yahoo.com,http://www.ebay.com)])