Advertisement
Guest User

Untitled

a guest
Jun 15th, 2021
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.HashMap;
  3.  
  4. public class Graph {
  5.  
  6. // Each node maps to a list of all his neighbors
  7. private HashMap<Node, LinkedList<Node>> adjacencyMap;
  8. private boolean directed;
  9.  
  10. public Graph(boolean directed) {
  11. this.directed = directed;
  12. adjacencyMap = new HashMap<>();
  13. }
  14.  
  15. public void addEdgeHelper(Node a, Node b) {
  16. LinkedList<Node> tmp = adjacencyMap.get(a);
  17.  
  18. if (tmp != null) {
  19. tmp.remove(b);
  20. }
  21. else tmp = new LinkedList<>();
  22. tmp.add(b);
  23. adjacencyMap.put(a,tmp);
  24. }
  25.  
  26. public void addEdge(Node source, Node destination) {
  27.  
  28. // We make sure that every used node shows up in our .keySet()
  29. if (!adjacencyMap.keySet().contains(source))
  30. adjacencyMap.put(source, null);
  31.  
  32. if (!adjacencyMap.keySet().contains(destination))
  33. adjacencyMap.put(destination, null);
  34.  
  35. addEdgeHelper(source, destination);
  36.  
  37. // If a graph is undirected, we want to add an edge from destination to source as well
  38. if (!directed) {
  39. addEdgeHelper(destination, source);
  40. }
  41. }
  42.  
  43.  
  44. public void printEdges() {
  45. for (Node node : adjacencyMap.keySet()) {
  46. System.out.print("The " + node.name + " has an edge towards: ");
  47. if (adjacencyMap.get(node) != null) {
  48. for (Node neighbor : adjacencyMap.get(node)) {
  49. System.out.print(neighbor.name + " ");
  50. }
  51. System.out.println();
  52. }
  53. else {
  54. System.out.println("none");
  55. }
  56. }
  57. }
  58.  
  59. public boolean hasEdge(Node source, Node destination) {
  60. return adjacencyMap.containsKey(source) && adjacencyMap.get(source) != null && adjacencyMap.get(source).contains(destination);
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement