前言
有向图(Directed Graph)是一种由顶点和有方向的边组成的图数据结构。
实现原理
使用邻接表表示法实现有向图相对简单明了,步骤也相对简单。
1:首先创建有向图
2.创建顶点
3.顶点间创建边
具体代码实现
java
package test13;
import java.util.*;
class Vertex {
private String label;
public Vertex(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Vertex vertex = (Vertex) obj;
return label.equals(vertex.label);
}
@Override
public int hashCode() {
return label.hashCode();
}
@Override
public String toString() {
return label;
}
}
class DirectedGraph {
private Map<Vertex, List<Vertex>> adjVertices;
public DirectedGraph() {
adjVertices = new HashMap<>();
}
public void addVertex(String label) {
adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
}
public void removeVertex(String label) {
Vertex v = new Vertex(label);
adjVertices.values().forEach(e -> e.remove(v));
adjVertices.remove(new Vertex(label));
}
public void addEdge(String label1, String label2) {
Vertex v1 = new Vertex(label1);
Vertex v2 = new Vertex(label2);
adjVertices.get(v1).add(v2);
}
public void removeEdge(String label1, String label2) {
Vertex v1 = new Vertex(label1);
Vertex v2 = new Vertex(label2);
List<Vertex> eV1 = adjVertices.get(v1);
if (eV1 != null)
eV1.remove(v2);
}
public List<Vertex> getAdjVertices(String label) {
return adjVertices.get(new Vertex(label));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Vertex v : adjVertices.keySet()) {
sb.append(v).append(": ");
for (Vertex w : adjVertices.get(v)) {
sb.append(w).append(" ");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
DirectedGraph graph = new DirectedGraph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "C");
graph.addEdge("C", "D");
System.out.println(graph);
}
}
QA:待定