- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacencyMatrixGraph.java
More file actions
Latest commit
69 lines (57 loc) · 2.1 KB
/
Copy pathAdjacencyMatrixGraph.java
File metadata and controls
69 lines (57 loc) · 2.1 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
packagegraph_algorithms;
importdata_structures.LinkedList;
publicclassAdjacencyMatrixGraphextendsGraph {
publicfinaldouble[][] adjacencyMatrix;
publicAdjacencyMatrixGraph(intn, booleandirected) {
super(n, directed);
adjacencyMatrix = newdouble[n][n];
for (intfrom = 0; from < adjacencyMatrix.length; ++from) {
for (intto = 0; to < adjacencyMatrix[from].length; ++to) {
if (from == to) {
adjacencyMatrix[from][to] = 0;
} else {
adjacencyMatrix[from][to] = Double.POSITIVE_INFINITY;
}
}
}
}
publicstaticvoidmain(String[] args) {
// Examples:
// Undirected
Graphgraph = newAdjacencyMatrixGraph(4, false);
constructExampleGraph(graph);
System.out.println(graph.containsEdge(1, 3)); // true
System.out.println(graph.outEdges(3).size()); // 3
System.out.println(graph.getVertexCount()); // 4
System.out.println(graph.getEdgeCount()); // 5
// Directed
Graphdigraph = newAdjacencyMatrixGraph(4, true);
constructExampleGraph(digraph);
System.out.println(digraph.containsEdge(1, 3)); // false
System.out.println(digraph.outEdges(3).size()); // 2
System.out.println(digraph.getVertexCount()); // 4
System.out.println(digraph.getEdgeCount()); // 5
}
@Override
publicbooleancontainsEdge(intfrom, intto) {
returnadjacencyMatrix[from][to] != Double.POSITIVE_INFINITY;
}
@Override
publicLinkedList<Integer> outEdges(intvertex) {
LinkedList<Integer> out = newLinkedList<>();
for (intto = 0; to < adjacencyMatrix[vertex].length; ++to) {
if (containsEdge(vertex, to)) {
out.addLast(to);
}
}
returnout;
}
@Override
protectedvoid_addEdge(intfrom, intto, doublecost) {
adjacencyMatrix[from][to] = cost;
}
@Override
publicdoublecost(intfrom, intto) {
returnadjacencyMatrix[from][to];
}
}