Created
April 20, 2016 14:57
-
-
Save ibogun/14ee40824836ed26b9e4ef72245abbde to your computer and use it in GitHub Desktop.
Graph.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package graphs; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
public class Graph { | |
private int V; | |
private int E = 0; | |
private List<Integer>[] adj; | |
@SuppressWarnings("unchecked") | |
public Graph(int V_) { | |
this.V = V_; | |
adj = new List[V_]; | |
for (int i = 0; i < adj.length; i++) { | |
adj[i] = new ArrayList<Integer>(); | |
} | |
} | |
public List<Integer> adj(int v) { | |
return adj[v]; | |
} | |
public void addDirectedEdge(int from, int to) { | |
if (!adj[from].contains(to)) { | |
E++; | |
adj[from].add(to); | |
} | |
} | |
public void addUndirectedEdge(int from, int to) { | |
addDirectedEdge(from, to); | |
addDirectedEdge(to, from); | |
} | |
public int V() { | |
return V; | |
} | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
sb.append("Graph with V = " + V + " , E = " + E + "\n"); | |
for (int i = 0; i < this.V(); i++) { | |
sb.append(i + ": "); | |
sb.append(adj[i]); | |
sb.append("\n"); | |
} | |
return new String(sb); | |
} | |
private class VertexIterator implements Iterator<Integer> { | |
private int vertex = 0; | |
@Override | |
public boolean hasNext() { | |
return (vertex < Graph.this.V); | |
} | |
@Override | |
public Integer next() { | |
int current = vertex; | |
vertex++; | |
return current; | |
} | |
@Override | |
public void remove() { | |
// TODO Auto-generated method stub | |
} | |
} | |
public Iterator<Integer> iterateVertices() { | |
return new VertexIterator(); | |
} | |
public Iterator<Integer> iterateEdges(int v) { | |
return this.adj[v].iterator(); | |
} | |
public static void main(String[] args) { | |
int V = 2; | |
Graph g = new Graph(V); | |
System.out.println(g); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment