Advertisement
Guest User

Graph Adjacency List

a guest
Nov 12th, 2017
1,020
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package dijkstra;
  2.  
  3. import java.util.Iterator;
  4. import java.util.PriorityQueue;
  5.  
  6. public class Graph {
  7.     private int vCount;
  8.     private PriorityQueue<Edge>[] adj;
  9.  
  10.     public int getvCount() {
  11.         return vCount;
  12.     }
  13.  
  14.     public Graph(int vCount) {
  15.         this.vCount = vCount;
  16.         // initialize adj
  17.         adj = new PriorityQueue[vCount];
  18.         for (int i = 0; i < vCount; i++) {
  19.             adj[i] = new PriorityQueue<Edge>();
  20.         }
  21.     }
  22.  
  23.     public void addEdge(int i, int j, float weight) {
  24.         adj[i].add(new Edge(i, j, weight));
  25.     }
  26.  
  27.     public void addEdge(Edge e) {
  28.         adj[e.getStartPoint()].add(e);
  29.     }
  30.  
  31.     public void removeEdge(int i, int j) {
  32.         Iterator<Edge> it = adj[i].iterator();
  33.         Edge other = new Edge(i, j, 0);
  34.         while (it.hasNext()) {
  35.             if (it.next().equals(other)) {
  36.                 it.remove();
  37.                 return;
  38.             }
  39.         }
  40.     }
  41.  
  42.     public boolean hasEdge(Edge e) {
  43.         return adj[e.getStartPoint()].contains(e);
  44.     }
  45.  
  46.     public PriorityQueue<Edge> neighbours(int vertex) {
  47.         return adj[vertex];
  48.     }
  49.  
  50.     public void printGraph() {
  51.         for (int i = 0; i < vCount; i++) {
  52.             PriorityQueue<Edge> edges = neighbours(i);
  53.             Iterator<Edge> it = edges.iterator();
  54.             System.out.print(i + ": ");
  55.             for (int j = 0; j < edges.size(); j++) {
  56.                 System.out.print(it.next() + " ");
  57.             }
  58.             System.out.println();
  59.         }
  60.     }
  61. }
Advertisement
RAW Paste Data Copied
Advertisement