aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/MatrixGraph.java
blob: 41d5880d71150697e5a5b3a784ddc5d4048353d2 (plain)
  1. package com.example.portfolio3;
  2. // origin: <https://moodle.ruc.dk/course/section.php?id=211877>
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7. /// Matrix Graph: weights are stored in a twodimensional array
  8. public class MatrixGraph extends AbstractGraph {
  9. /// foo
  10. private Integer[][] matrix = null; // made in constructor
  11. /// foo
  12. // We must be able to map vertices to index in matrix and back again
  13. private Vertex[] index2vertex; // made in constructor
  14. /// foo
  15. private Map<Vertex, Integer> vertex2index = new HashMap<>();
  16. /// maximum number of vertices
  17. private int numVertex;
  18. /// foo
  19. ///
  20. /// @param numVertex maximum number of vertices allowed
  21. public MatrixGraph(final int numVertex) {
  22. this.numVertex = numVertex;
  23. matrix = new Integer[numVertex][numVertex];
  24. index2vertex = new Vertex[numVertex];
  25. }
  26. /// foo
  27. ///
  28. /// @param v vertex
  29. /// @return int
  30. private int getIndex(final Vertex v) {
  31. if (vertex2index.containsKey(v)) {
  32. return vertex2index.get(v);
  33. }
  34. int index = vertex2index.size();
  35. if (index >= index2vertex.length) {
  36. throw new RuntimeException("Too many vertices in graph");
  37. }
  38. vertex2index.put(v, index);
  39. index2vertex[index] = v;
  40. return index;
  41. }
  42. /// foo
  43. public final void insertEdge(final Vertex v1, final Vertex v2, final int w) {
  44. matrix[getIndex(v1)][getIndex(v2)] = w;
  45. }
  46. /// foo
  47. public final Collection<Edge> edges() {
  48. HashSet<Edge> edges = new HashSet<>();
  49. for (int i = 0; i < numVertex; i++) {
  50. for (int j = 0; j < numVertex; j++) {
  51. Integer weight = matrix[i][j]; // may be null
  52. if (weight == null) {
  53. continue;
  54. }
  55. edges.add(new Edge(index2vertex[i], index2vertex[j], weight));
  56. }
  57. }
  58. return edges;
  59. }
  60. /// foo
  61. public final Collection<Edge> outEdge(final Vertex v1) {
  62. HashSet<Edge> edges = new HashSet<>();
  63. int i = vertex2index.get(v1);
  64. for (int j = 0; j < numVertex; j++) {
  65. Integer weight = matrix[i][j]; // may be null
  66. if (weight == null) {
  67. continue;
  68. }
  69. edges.add(new Edge(v1, index2vertex[j], weight));
  70. }
  71. return edges;
  72. }
  73. /// foo
  74. public final Integer getWeight(final Vertex v1, final Vertex v2) {
  75. // constant time operation
  76. return matrix[vertex2index.get(v1)][vertex2index.get(v2)];
  77. }
  78. }