java邻接图_具有有向加权边的图的Java邻接列表实现(Java Adjacency list implementation of graph with directed weighted edge...
时间: 2024-03-06 11:49:01 浏览: 109
图的邻接表的实现带权路径
以下是一个基于Java的邻接列表实现,用于表示具有有向加权边的图:
```
import java.util.ArrayList;
import java.util.List;
public class WeightedGraph {
private List<List<Edge>> adjacencyList;
public WeightedGraph(int vertices) {
adjacencyList = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
adjacencyList.add(new ArrayList<>());
}
}
public void addEdge(int source, int destination, int weight) {
Edge edge = new Edge(source, destination, weight);
adjacencyList.get(source).add(edge);
}
public List<Edge> getEdges(int source) {
return adjacencyList.get(source);
}
public static class Edge {
int source;
int destination;
int weight;
public Edge(int source, int destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
public int getSource() {
return source;
}
public int getDestination() {
return destination;
}
public int getWeight() {
return weight;
}
}
}
```
这个实现使用了一个包含列表的列表来表示邻接列表,其中每个元素表示图中一个顶点的邻居节点。每个顶点的邻居节点用 Edge 类表示,其中包含源顶点、目标顶点和边权重。addEdge() 方法用于将边添加到邻接列表中,getEdges() 方法用于获取给定顶点的邻居节点列表。
阅读全文