aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/MatrixGraph.java
blob: aac47265203410c5b2eb4c283c832ec61f06b684 (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. /// foo
  17. private int numVertex; // maximum number of vertices
  18. /// foo
  19. /// @param numVertex maximum number of vertices allowed
  20. public MatrixGraph(int numVertex){
  21. this.numVertex=numVertex;
  22. matrix =new Integer[numVertex][numVertex];
  23. index2vertex=new Vertex[numVertex];
  24. }
  25. /// foo
  26. /// @param v vertex
  27. /// @return int
  28. private int getIndex(Vertex v){
  29. if(vertex2index.containsKey(v)) return vertex2index.get(v);
  30. int index=vertex2index.size();
  31. if(index>=index2vertex.length)throw new RuntimeException("Too many vertices in graph");
  32. vertex2index.put(v,index);
  33. index2vertex[index]=v;
  34. return index;
  35. }
  36. /// foo
  37. public void insertEdge(Vertex v1,Vertex v2,int w){
  38. matrix[getIndex(v1)][getIndex(v2)] = w;
  39. }
  40. /// foo
  41. public Collection<Edge> edges(){
  42. HashSet<Edge> edges=new HashSet<>();
  43. for(int i=0;i<numVertex;i++){
  44. for(int j=0;j<numVertex;j++){
  45. Integer weight=matrix[i][j]; // may be null
  46. if(weight==null)continue;
  47. edges.add(new Edge(index2vertex[i],index2vertex[j],weight));
  48. }
  49. }
  50. return edges;
  51. }
  52. /// foo
  53. public Collection<Edge> outEdge(Vertex v1){
  54. HashSet<Edge> edges=new HashSet<>();
  55. int i=vertex2index.get(v1);
  56. for(int j=0;j<numVertex;j++){
  57. Integer weight=matrix[i][j]; // may be null
  58. if(weight==null)continue;
  59. edges.add(new Edge(v1,index2vertex[j],weight));
  60. }
  61. return edges;
  62. }
  63. /// foo
  64. public Integer getWeight(Vertex v1,Vertex v2){
  65. // constant time operation
  66. return matrix[vertex2index.get(v1)][vertex2index.get(v2)];}
  67. }