加权有向边的API
API | 功能 |
---|---|
double weight() | 边的权重 |
int from() | 指出这条边的顶点 |
int to() | 这条边指向的顶点 |
String toString() | 对象的字符串表示 |
加权有向图的API
API | 功能 |
---|---|
EdgeWeightedDigraph(int V) | 含有V个顶点的空有向图 |
EdgeWeightedDigraph(int vn, int en, int[][] data, double[] weights) | 读取图的构造函数 |
int V() | 顶点总数 |
int E() | 边的总数 |
void addEdge(DirectedEdge e) | 将e添加到该有向图中 |
Iterable<DirectedEdge> adj(int v) | 从v指出的边 |
Iterable<DirectedEdge> edges() | 该有向图中的所有边 |
String toString() | 对象的字符串表示 |
实现
DirectedEdge.java
package section4_4;
public class DirectedEdge {
private final int v;
private final int w;
private final double weight;
public DirectedEdge(int v, int w, double weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
public double weight() {
return weight;
}
public int from() {
return v;
}
public int to() {
return w;
}
public String toString() {
return String.format("%d->%d %.2f",v,w,weight);
}
}
EdgeWeightedDigraph.java
package section4_4;
import section1_3.Bag;
public class EdgeWeightedDigraph {
private final int V;
private int E;
private Bag<DirectedEdge>[] adj;
public EdgeWeightedDigraph(int V) {
this.V = V;
this.E = 0;
adj = (Bag<DirectedEdge>[]) new Bag[V];
for (int v = 0;v < V;v++) {
adj[v] = new Bag<>();
}
}
public EdgeWeightedDigraph(int vn, int en, int[][] data, double[] weights) {
this(vn);
for (int i = 0;i < en;i++) {
DirectedEdge edge = new DirectedEdge(data[i][0],data[i][1],weights[i]);
addEdge(edge);
}
}
public int V() {
return V;
}
public int E() {
return E;
}
public void addEdge(DirectedEdge e) {
adj[e.from()].add(e);
E++;
}
public Iterable<DirectedEdge> adj(int v) {
return adj[v];
}
public Iterable<DirectedEdge> edges() {
Bag<DirectedEdge> bag = new Bag<>();
for (int v = 0;v < V;v++) {
for (DirectedEdge e : adj[v]) {
bag.add(e);
}
}
return bag;
}
}