-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
64 lines (55 loc) · 1.64 KB
/
Copy pathGraph.java
File metadata and controls
64 lines (55 loc) · 1.64 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
/*
* Sample usage: java Graph tinyG.txt
* Sample usage: java Graph mediumG.txt
*/
public class Graph {
private final int V; // number of vertices
private int E; // number of edges
private LinkedBag<Integer>[] adj; // adjacency lists
public Graph(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<>();
}
public Graph(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
adj[w].add(v); // add v to w'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 static void main(String[] args){
In in = new In(args[0]);
Graph G = new Graph(in);
StdOut.println(G);
}
}