Skip to content
Snippets Groups Projects
Graph.java 1.27 KiB
Newer Older
  • Learn to ignore specific revisions
  • public class Graph {
    
    	private final int V; // Number of nodes
    	private int E; // Number of edges
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	private Bag<Integer>[] adj; // Adjacency list for a node
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	public static void main(String[] args) {
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		Graph g = new Graph(5);
    		g.addEdge(4, 3);
    		g.addEdge(2, 3);
    		g.addEdge(1, 2);
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		g.addEdge(0, 2);
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		for(int i = 0; i < 5; i++)
    			System.out.println(g.adj(i));
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	}
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Constructor used to build a graph of a specified size
    	 * @param V The size of graph, or, the number of nodes in graph
    	 */
    
    	public Graph(int V){
    
    		this.V = V;
    		this.E = 0;
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		adj = (Bag<Integer>[]) new Bag[V];
    
    		for(int v = 0; v < V; v++)
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    			adj[v] = new Bag<Integer>(); 
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Accesses the number of vertices
    	 * @return The number of vertices
    	 */
    
    	public int V(){
    		return V;
    	}
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Accesses the number of edges
    	 * @return The number of edges
    	 */
    
    	public int E(){
    		return E;
    	}
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Method to connect two vertices with an edge
    	 * @param v First vertex to be connected
    	 * @param w Second vertex to be connected
    	 */
    
    	public void addEdge(int v, int w){
    		adj[v].add(w);
    		adj[w].add(v);
    		E++;
    	}
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Method to access value in adjacency list
    	 * @param V Vertex to be accessed
    	 * @return Value of vertex V
    	 */
    
    	public Iterable<Integer> adj(int V){
    		return adj[V];
    	}