Advertisement
Aldin_SXR

Graph.class

May 26th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. package ds.undirected.graph;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5.  
  6. public class Graph {
  7.     private int V;                      // number of vertices
  8.     private int E;                      // number of edges
  9.     private ArrayList<Integer>[] adj;   // adjacency lists
  10.    
  11.     /* Create a Graph with V vertices and no edges */
  12.     @SuppressWarnings("unchecked")
  13.     public Graph(int V) {
  14.         this.V = V;
  15.         this.E = 0;
  16.         adj = (ArrayList<Integer>[]) new ArrayList[V];  // create an array of lists
  17.         for (int v = 0; v < V; v++) {                   // initialize all lists
  18.             adj[v] = new ArrayList<Integer>();          // the lists will hold adjacent vertices
  19.         }
  20.     }
  21.    
  22.     /* Create a graph from an input stream (e.g. file) */
  23.     public Graph(Scanner in) {
  24.         /* The first file line is V, the number of vertices*/
  25.         this(in.nextInt());                 // construct the graph using V  
  26.         int E = in.nextInt();               // the next line is E, the number of edges
  27.        
  28.         for (int i = 0; i < E; i++) {       // iterate over all edges
  29.             int v = in.nextInt();           // read one vertex
  30.             int w = in.nextInt();           // read the other vertex
  31.             addEdge(v, w);                  // add an edge between vertex v and w
  32.         }
  33.     }
  34.    
  35.     /* Return the number of vertices */
  36.     public int V() {
  37.         return V;
  38.     }
  39.    
  40.     /* Return the number of edges */
  41.     public int E() {
  42.         return E;
  43.     }
  44.    
  45.     /* Add a new edge to the graph */
  46.     public void addEdge(int v, int w) {
  47.         /* Since this is an undirected graph, v is connected to w
  48.          * and w is connected to v */
  49.         adj[v].add(w);  // connect v to w
  50.         adj[w].add(v);  // connect w to v
  51.         E++;            // increment the number of edges
  52.     }
  53.    
  54.     /* Return adjacent vertices for a vertex v */
  55.     public Iterable<Integer> adj(int v) {
  56.         return adj[v];
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement