-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDigraph.java
83 lines (73 loc) · 1.9 KB
/
Digraph.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import edu.princeton.cs.algs4.*;
public class Digraph{
private final int V;
private int E;
private Bag<Integer>[] adj;
private static final String NEWLINE = System.getProperty("line.separator");
public Digraph(int V){
this.V = V;
this.E = 0;
adj = (Bag<Integer>[]) new Bag[V];
for(int v=0; v < V; v++){
adj[v] = new Bag<Integer>();
}
}
public Digraph(In in) {
this.V = in.readInt();
adj = (Bag<Integer>[]) new Bag[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
}
int E = in.readInt();
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
addEdge(v, w);
}
}
public int V(){
return V;
}
public int E(){
return E;
}
public void addEdge(int v, int w){
adj[v].add(w);
E++;
}
public Iterable<Integer> adj(int v){
return adj[v];
}
public Digraph inverse(){
Digraph R = new Digraph(V);
for(int v = 0; v < V; v++){
for(int w : adj[v]){
R.addEdge(w, v);
}
}
return R;
}
public String toString(){
StringBuilder s = new StringBuilder();
s.append(V + " vertices, " + E + " edges " + NEWLINE);
for(int v=0; v < V; v++){
s.append(String.format("%d: ", v));
for(int w : adj(v)){
s.append(String.format("%d ", w));
}
s.append(NEWLINE);
}
return s.toString();
}
/**
* Unit tests the {@code Digraph} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in = new In(args[0]);
Digraph G = new Digraph(in);
StdOut.println(G);
StdOut.println(G.inverse());
}
}