-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgraph.java
More file actions
59 lines (48 loc) · 1.53 KB
/
graph.java
File metadata and controls
59 lines (48 loc) · 1.53 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
package data.structures;
public class graph {
int size;
String[] vertices;
boolean[][] a;
graph(String[] args) {
size = args.length;
vertices = new String[size];
System.arraycopy(args, 0, vertices, 0, size);
a = new boolean[size][size];
}
public void add(String v, String w) {
int i = index(v);
int j = index(w);
a[i][j] = a[j][i] = true;
}
private int index(String vertex) {
for (int i = 0; i < size; i++)
if (vertex.equals(vertices[i]))
return i;
throw new IllegalArgumentException("Wrong values to be added.");
}
@Override
public String toString() {
if (size == 0) return "";
StringBuffer buff = new StringBuffer("{ " + vertex(0));
for (int i = 1; i < size; i++)
buff.append(", ").append(vertex(i));
return buff + " }";
}
private String vertex(int i) {
StringBuffer buff = new StringBuffer(vertices[i] + ":");
for (int j = 0; j < size; j++)
if (a[i][j])
buff.append(vertices[j]);
return buff + "";
}
public static void main(String[] args) {
String[] a = {"A", "B", "C", "D"};
graph myGraph = new graph(a);
myGraph.add("A", "B");
myGraph.add("A", "D");
myGraph.add("B", "C");
myGraph.add("B", "D");
myGraph.add("C", "D");
System.out.println(myGraph.toString());
}
}