Created
December 2, 2016 09:44
-
-
Save rohithpeddi/52dae1eb7ddead27ee2082fdba94462f to your computer and use it in GitHub Desktop.
EdgeWeightedGraph with ADJACENCY MATRIX implementation
This file contains hidden or 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
static class EdgeWeightedGraph{ | |
Edge[][] adj; | |
int noOfVertices; | |
public EdgeWeightedGraph(int v){ | |
this.adj = new Edge[v+1][v+1]; | |
this.noOfVertices = v+1; | |
} | |
public void addEdge(Edge edge) { | |
int v = edge.eitherVertex(), w = edge.otherVertex(v); | |
if (adj[v][w] == null) { | |
adj[v][w] = edge; | |
adj[w][v] = edge; | |
} | |
else{ | |
if(adj[v][w].getWeight() > edge.getWeight()){ | |
adj[v][w] = edge; | |
adj[w][v] = edge; | |
} | |
} | |
} | |
public ArrayList<Edge> getAdjEdges(int v) { | |
ArrayList<Edge> edges = new ArrayList<Edge>(); | |
for(int i=1;i<noOfVertices;i++){ | |
if(adj[v][i] != null){ | |
edges.add(adj[v][i]); | |
} | |
} | |
return edges; | |
} | |
private ArrayList<Integer> getAdjVertices(int v){ | |
ArrayList<Integer> adjVertices = new ArrayList<Integer>(); | |
for(Edge e : getAdjEdges(v)){ | |
adjVertices.add(e.otherVertex(v)); | |
} | |
return adjVertices; | |
} | |
public void printGraph() { | |
for (int i = 1; i < noOfVertices; i++) { | |
System.out.print(i + " :"); | |
for (Edge e : getAdjEdges(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