summaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/MatrixGraph.java
blob: 5a1f327c96892e12cec325777531bec1f7e89288 (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. int index = vertex2index.size();
  34. if (index >= index2vertex.length)
  35. throw new RuntimeException("Too many vertices in graph");
  36. vertex2index.put(v, index);
  37. index2vertex[index] = v;
  38. return index;
  39. }
  40. /// foo
  41. public void insertEdge(final Vertex v1, final Vertex v2, final int w) {
  42. matrix[getIndex(v1)][getIndex(v2)] = w;
  43. }
  44. /// foo
  45. public Collection<Edge> edges() {
  46. HashSet<Edge> edges = new HashSet<>();
  47. for (int i = 0; i < numVertex; i++) {
  48. for (int j = 0; j < numVertex; j++) {
  49. Integer weight = matrix[i][j]; // may be null
  50. if (weight == null) continue;
  51. edges.add(new Edge(index2vertex[i],index2vertex[j],weight));
  52. }
  53. }
  54. return edges;
  55. }
  56. /// foo
  57. public Collection<Edge> outEdge(final Vertex v1) {
  58. HashSet<Edge> edges = new HashSet<>();
  59. int i = vertex2index.get(v1);
  60. for (int j = 0; j < numVertex; j++) {
  61. Integer weight = matrix[i][j]; // may be null
  62. if (weight == null) continue;
  63. edges.add(new Edge(v1,index2vertex[j],weight));
  64. }
  65. return edges;
  66. }
  67. /// foo
  68. public Integer getWeight(final Vertex v1, final Vertex v2) {
  69. // constant time operation
  70. return matrix[vertex2index.get(v1)][vertex2index.get(v2)];
  71. }
  72. }