在上一篇文章中,我们初步认识了Graph接口。本篇文章中,我们将编写一个简单的测试程序,测试Graph接口。我们将使用DefaultDirectedGraph(默认的有向图)类作为Graph接口的实现类。
我们将创建这样的一个图:
代码如下:
import org.jgrapht.*;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
public class TestGraphInterface {
public static void main(String[] args) {
Graph<String, DefaultEdge> cityCN = new DefaultDirectedGraph<>(DefaultEdge.class);
String city1 = "Beijing";
String city2 = "Shanghai";
String city3 = "Guangzhou";
String city4 = "Shenzhen";
cityCN.addVertex(city1);
cityCN.addVertex(city2);
cityCN.addVertex(city3);
cityCN.addVertex(city4);
cityCN.addEdge(city1, city2); //Beijing to Shanghai
cityCN.addEdge(city2, city3); //Shanghai to Guangzhou
cityCN.addEdge(city3, city4); //Guangzhou to Shenzhen
//Is there an edge from Beijing to Guangzhou? No.
System.out.println(cityCN.getEdge(city1, city3));
//Is there an edge from Shanghai to Beijing? No.
System.out.println(cityCN.getEdge(city2, city1));
//Is there an edge from Beijing to Shanghai? Yes.
System.out.println(cityCN.getEdge(city1, city2));
}
}
运行以上代码,输出结果为:
null
null
(Beijing : Shanghai)
cityCN.getEdge(city1, city3)为null,说明不存在从city1到city3的边(虽然有从city1到city3的路径,但它是经过city2的,不是直接从city1到city3的)。
cityCN.getEdge(city2, city1)为null,说明不存在从city2到city1的边。图cityCN的边有方向性,从city1到city2的边和从city2到city1的边不是同一条边。
cityCN.getEdge(city1, city2)不为null,说明存在从city1到city2的边。