-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacencyMatrixGraph.java
More file actions
69 lines (57 loc) · 2.1 KB
/
AdjacencyMatrixGraph.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
package graph_algorithms;
import data_structures.LinkedList;
public class AdjacencyMatrixGraph extends Graph {
public final double[][] adjacencyMatrix;
public AdjacencyMatrixGraph(int n, boolean directed) {
super(n, directed);
adjacencyMatrix = new double[n][n];
for (int from = 0; from < adjacencyMatrix.length; ++from) {
for (int to = 0; to < adjacencyMatrix[from].length; ++to) {
if (from == to) {
adjacencyMatrix[from][to] = 0;
} else {
adjacencyMatrix[from][to] = Double.POSITIVE_INFINITY;
}
}
}
}
public static void main(String[] args) {
// Examples:
// Undirected
Graph graph = new AdjacencyMatrixGraph(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
Graph digraph = new AdjacencyMatrixGraph(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
public boolean containsEdge(int from, int to) {
return adjacencyMatrix[from][to] != Double.POSITIVE_INFINITY;
}
@Override
public LinkedList<Integer> outEdges(int vertex) {
LinkedList<Integer> out = new LinkedList<>();
for (int to = 0; to < adjacencyMatrix[vertex].length; ++to) {
if (containsEdge(vertex, to)) {
out.addLast(to);
}
}
return out;
}
@Override
protected void _addEdge(int from, int to, double cost) {
adjacencyMatrix[from][to] = cost;
}
@Override
public double cost(int from, int to) {
return adjacencyMatrix[from][to];
}
}