在Java中,實(shí)現(xiàn)拓?fù)鋱D可以通過(guò)使用鄰接表或鄰接矩陣來(lái)表示圖。這里我將給出一個(gè)使用鄰接表實(shí)現(xiàn)的簡(jiǎn)單示例。拓?fù)鋱D是有向無(wú)環(huán)圖(Directed Acyclic Graph,簡(jiǎn)稱DAG)的一種應(yīng)用場(chǎng)景。
首先,我們需要?jiǎng)?chuàng)建一個(gè)表示圖的類,包括頂點(diǎn)和邊。然后,我們可以使用深度優(yōu)先搜索(DFS)或廣度優(yōu)先搜索(BFS)來(lái)遍歷圖并實(shí)現(xiàn)拓?fù)渑判颉?/p>
以下是一個(gè)簡(jiǎn)單的實(shí)現(xiàn):
public class Vertex {
private String label;
private List<Vertex> neighbors;
public Vertex(String label) {
this.label = label;
this.neighbors = new ArrayList<>();
}
public void addNeighbor(Vertex neighbor) {
this.neighbors.add(neighbor);
}
public String getLabel() {
return label;
}
public List<Vertex> getNeighbors() {
return neighbors;
}
}
public class Graph {
private List<Vertex> vertices;
public Graph() {
this.vertices = new ArrayList<>();
}
public void addVertex(Vertex vertex) {
this.vertices.add(vertex);
}
public List<Vertex> getVertices() {
return vertices;
}
}
public class TopologicalSort {
public static List<Vertex> topologicalSort(Graph graph) {
List<Vertex> sortedVertices = new ArrayList<>();
Set<Vertex> visitedVertices = new HashSet<>();
for (Vertex vertex : graph.getVertices()) {
if (!visitedVertices.contains(vertex)) {
dfs(vertex, visitedVertices, sortedVertices);
}
}
Collections.reverse(sortedVertices);
return sortedVertices;
}
private static void dfs(Vertex currentVertex, Set<Vertex> visitedVertices, List<Vertex> sortedVertices) {
visitedVertices.add(currentVertex);
for (Vertex neighbor : currentVertex.getNeighbors()) {
if (!visitedVertices.contains(neighbor)) {
dfs(neighbor, visitedVertices, sortedVertices);
}
}
sortedVertices.add(currentVertex);
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph();
Vertex v1 = new Vertex("1");
Vertex v2 = new Vertex("2");
Vertex v3 = new Vertex("3");
Vertex v4 = new Vertex("4");
Vertex v5 = new Vertex("5");
graph.addVertex(v1);
graph.addVertex(v2);
graph.addVertex(v3);
graph.addVertex(v4);
graph.addVertex(v5);
v1.addNeighbor(v2);
v1.addNeighbor(v3);
v2.addNeighbor(v4);
v3.addNeighbor(v4);
v4.addNeighbor(v5);
List<Vertex> sortedVertices = TopologicalSort.topologicalSort(graph);
for (Vertex vertex : sortedVertices) {
System.out.print(vertex.getLabel() + " ");
}
}
}
輸出結(jié)果:
1 3 2 4 5
這個(gè)示例展示了如何在Java中實(shí)現(xiàn)拓?fù)鋱D。你可以根據(jù)自己的需求對(duì)這個(gè)實(shí)現(xiàn)進(jìn)行擴(kuò)展和修改。