Skip to content

Instantly share code, notes, and snippets.

@rohithpeddi
Last active December 2, 2016 09:45
Show Gist options
  • Save rohithpeddi/321dc196b0cc861be433da5517f419d7 to your computer and use it in GitHub Desktop.
Save rohithpeddi/321dc196b0cc861be433da5517f419d7 to your computer and use it in GitHub Desktop.
Undirected Graph Data Stucture with edge weights and ADJACENCY LIST implementation
static class EdgeWeightedGraph {
ArrayList<ArrayList<Edge>> adj;
int noOfVertices;
public EdgeWeightedGraph(int v) {
this.adj = new ArrayList<ArrayList<Edge>>(v + 1);
this.noOfVertices = v+1;
// Vertices start from 1, ignore the list at index 0
for (int l = 0; l <= v; l++) {
adj.add(new ArrayList<Edge>());
}
}
private ArrayList<Edge> getAdjEdges(int u){
return adj.get(u);
}
private ArrayList<Integer> getAdjVertices(int u){
ArrayList<Integer> adjVertices = new ArrayList<Integer>();
for(Edge e : adj.get(u)){
adjVertices.add(e.otherVertex(u));
}
return adjVertices;
}
private void addEdge(Edge edge) {
int u = edge.eitherVertex(), w = edge.otherVertex(u);
adj.get(u).add(edge);
adj.get(w).add(edge);
}
private void removeEdge(Edge edge) {
int u = edge.eitherVertex(), w = edge.otherVertex(u);
adj.get(u).remove(edge);
adj.get(w).remove(edge);
}
public void printGraph() {
for (int i = 1; i < adj.size(); i++) {
System.out.print(i + " :");
for (Edge e : adj.get(i)) {
System.out.print(e + ",");
}
System.out.println();
}
}
}
static class Edge implements Comparable<Edge> {
int u;
int v;
int weight;
public Edge(int u, int v, int weight) {
this.u = u;
this.v = v;
this.weight = weight;
}
public int compareTo(Edge that) {
return Integer.compare(this.weight, that.weight);
}
public int eitherVertex() {
return u;
}
public int otherVertex(int x) {
return x == v ? u : v;
}
public int getWeight() {
return weight;
}
public String toString() {
return "( " + u + " -- " + v + ", " + weight + " )";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment