Skip to content

Instantly share code, notes, and snippets.

@jeewamp
Created December 1, 2012 09:37
Show Gist options
  • Select an option

  • Save jeewamp/4181310 to your computer and use it in GitHub Desktop.

Select an option

Save jeewamp/4181310 to your computer and use it in GitHub Desktop.
Make a graph Semi-Eulerian
/**
* Convert a Non-Eulerian to Semi-Eulerian. If graph is Eulerian or Semi-Eulerian, the graph will be
* immediately returned.
* @param adjacencyList, ArrayList of odd Vertices
* @return
*/
public <P extends Integer, Q extends ArrayList<P>> HashMap<P, Q>
convertToEulerian(HashMap<P, Q> adjacencyList, ArrayList<P> oddVertices){
if(oddVertices.size()<=2)
return adjacencyList;
//Number of vertices to be removed
int remove= oddVertices.size()-2;
//There are vertices to be removed. Find the vertices to be removed, such that the number of edges
//that would be removed will be minimal.
while (remove>0) {
Integer minDistance=Integer.MAX_VALUE;
P sourceOddV=null;
P destOddV=null;
//predecessor map for destination oddVertex
HashMap predecessorMapForD=null;
for (int j=0; j<oddVertices.size();j++) {
P oddVertex = oddVertices.get(j);
for (int k = j+1; k < oddVertices.size(); k++) {
P nextOddVertex = oddVertices.get(k);
BreadthFirstSearch<P> bfs = new <P>BreadthFirstSearch();
//BFS returns the two hashMaps distances (hashMaps[0]) and predecessors (hashMaps[1])
//with respect to oddVertex which is the source vertex for the BFS
HashMap[] hashMaps=bfs.BFS(adjacencyList,oddVertex,nextOddVertex);
Integer distance=(Integer)hashMaps[0].get(nextOddVertex);
if(distance<minDistance) {
minDistance=distance;
sourceOddV=oddVertex;
destOddV=nextOddVertex;
predecessorMapForD=hashMaps[1];
}
}
}
//Remove vertices in the path from sourceOddV to destOddV
ArrayList<P> pathToBeRemoved = new ArrayList<P>();
P tempVertex=destOddV;
while (tempVertex!=null) {
pathToBeRemoved.add(tempVertex);
tempVertex=(P)predecessorMapForD.get(tempVertex);
}
//Remove the edges. and the counted oddVertices.
for (int p = 0; p < pathToBeRemoved.size()-1; p++) {
P vertex1 = pathToBeRemoved.get(p);
P vertex2 = pathToBeRemoved.get(p+1);
adjacencyList = removeEdge(adjacencyList,vertex1,vertex2);
oddVertices.remove(sourceOddV);
oddVertices.remove(destOddV);
remove=remove-2;
}
}
return adjacencyList;
}
public <P extends Integer,Q extends ArrayList<P>> HashMap<P,Q> removeEdge(HashMap<P,Q> adjList, P v1, P v2) {
if(!adjList.get(v1).contains(v2))
return adjList;
adjList.get(v1).remove(v2);
adjList.get(v2).remove(v1);
return adjList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment