-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeightedGraph.java
More file actions
96 lines (73 loc) · 1.69 KB
/
WeightedGraph.java
File metadata and controls
96 lines (73 loc) · 1.69 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.ArrayList;
import java.util.Random;
import nodes.Vertex;
import nodes.Edge;
public class WeightedGraph {
private ArrayList<Vertex> V;
private ArrayList<Edge> E;
public WeightedGraph() {
V = new ArrayList<Vertex>();
E = new ArrayList<Edge>();
}
public void addEdge(int weight, Vertex a, Vertex b) {
if (!(V.contains(a) && V.contains(b))) {
System.out.println("Error: at least one endpoint does not exist in the graph");
return;
}
Edge e = new Edge(weight, a, b);
E.add(e);
}
public void addVertex(Vertex a) {
if (V.contains(a)) {
System.out.println("Graph already contains vertex");
return;
}
V.add(a);
}
public void primMST() {
}
public void kruskalMST() {
}
public void dikstraSP() {
}
public Vertex getVertex(int val) {
for (Vertex v : V) {
if (v.value == val) {
return v;
}
}
return null;
}
public void printVertices() {
for (Vertex v : V) {
System.out.println(v.value + " ");
}
}
public void printEdges() {
for (Edge e : E) {
Vertex adj[] = e.getVertices();
System.out.println(adj[0].value + "-" + adj[1].value + " (" + e.weight + ")" );
}
}
public void printGraph() {
System.out.println("Vertices: ");
printVertices();
System.out.println("Edges: ");
printEdges();
}
// unit test with simple K4 graph
public static void main(String args[]) {
Random rand = new Random();
WeightedGraph G = new WeightedGraph();
for (int i = 0; i < 4; i++) {
Vertex v = new Vertex(i);
G.addVertex(v);
}
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
G.addEdge(rand.nextInt(100), G.getVertex(i), G.getVertex(j));
}
}
G.printGraph();
}
}