-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDigraph.java
More file actions
71 lines (61 loc) · 1.8 KB
/
Copy pathDigraph.java
File metadata and controls
71 lines (61 loc) · 1.8 KB
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
/*
* Sample usage: java Digraph tinyDG.txt
* Sample usage: java Digraph mediumDG.txt
*/
public class Digraph {
private final int V; // number of vertices
private int E; // number of edges
private LinkedBag<Integer>[] adj; // adjacency lists
public Digraph(int V){
this.V = V;
this.E = 0;
adj = (LinkedBag<Integer>[]) new LinkedBag[V]; // Create array of lists
for (int v = 0; v < V; v++) // Initialize all lists to empty
adj[v] = new LinkedBag<Integer>();
}
public Digraph(In in){
this(in.readInt()); // read V and construct this graph
int E = in.readInt(); // read E
for (int i=0; i<E; i++){
// Add an edge
int v = in.readInt(); // read a vertex
int w = in.readInt(); // read another vertex
addEdge(v, w); // add edge connecting them
}
}
public int V(){
return V;
}
public int E(){
return E;
}
public void addEdge(int v, int w){
adj[v].add(w); // add w to v's list
E++;
}
public Iterable<Integer> adj(int v){
return adj[v];
}
public String toString(){
String s = V + " vertices, " + E + " edges\n";
for (int v=0; v < V; v++){
s += v + ": ";
for (int w : this.adj[v])
s += w + " ";
s += "\n";
}
return s;
}
public Digraph reverse(){
Digraph R = new Digraph(V);
for (int v=0; v<V; v++)
for (int w: adj(v))
R.addEdge(w, v);
return R;
}
public static void main(String[] args){
In in = new In(args[0]);
Digraph G = new Digraph(in);
StdOut.println(G);
}
}