# Graph, and a search that visits each edge exactly once in each direction

My assignment was to write a method that is capable of visiting each edge in a graph in each direction exactly once.

With it, I included a basic Graph class to test it with.

What I'd like a review of:

• This is like my 1000th attempt after trying everything I could think of. This is the first version that I've had that passes every test case I've presented it, so I'm pretty happy with it. I'm sure through all my refactoring though, I've made messes that I'm used to now. If anything could be simplified, I'd like to know.

• Is the Graph itself set-up well? This is my first time dealing with graphs, and while I'm fairly happy with it, I'm sure there are possible improvements.

• I want to return the path taken, but I also need to show that the resulting graph has been fully traversed. I can't easily return both without using a POD class. What are my options? I'd obviously like to avoid printing inside the method.

The graph I'm using in the example main is:

and the method in question is visitEachEdgeTwice. It works by constantly traversing un-touched edges, backtracking if necessary. To track which edges have been traversed, the edges are removed from a copy of the graph after they're traversed; disallowing them from being used again.

Graph.java:

package comp272.a3.q5;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

public class Graph<Vertex> {

// A map between a source vertex, and a list of targets that it connects to.
private HashMap<Vertex, HashSet<Vertex>> adj = new HashMap<Vertex, HashSet<Vertex>>();

public Graph() {

}

public Graph(Graph<Vertex> oldGraph) {
}

public Set<Vertex> getVertices() {
}

}

for (Vertex v : vertices) {
}
}

// Adds a directed (one-way) edge to the given vertex.
public void addDirectedToVertex(Vertex source, Vertex target) {
}

if (targets != null) {

} else {
throw new NoSuchElementException(
"Vertex " + source + " doesn't exist.");
}
}

// Adds an undirected (two-way) edge to the given vertices by adding 2
// directed edges between each vertex.
public void addUndirectedToVertex(Vertex source, Vertex target) {
}

// A convenience method for the question.
public void addUndirectedToVertex(Vertex source, List<Vertex> targets) {
for (Vertex target : targets) {
}
}

// A helper to remove all directed edges leading to a vertex.
private void removeAllEdgesTo(Vertex vertex) {
for (HashSet<Vertex> vs : adj.values()) {
vs.remove(vertex);
}
}

// Removes a vertex from the list; removing any edges associated with it.
public void removeVertex(Vertex vertex) {
removeAllEdgesTo(vertex);
}

// Removes the edge going from the source to the target (if any).
public void removeDirectedEdge(Vertex source, Vertex target) {

if (targets != null) {
targets.remove(target);

} else {
throw new NoSuchElementException(
"Vertex " + source + " doesn't exist.");
}
}

// Removes all edges going between the source and the target.
public void removeUndirectedEdge(Vertex source, Vertex target) {
removeDirectedEdge(source, target);
removeDirectedEdge(target, source);
}

// Returns whether or not the given edge exists.
public boolean hasEdge(Vertex source, Vertex target) {

if (targets == null) {
return false;

} else {
return targets.contains(target);
}
}

// Returns a list of outgoing edges from the given vertex.
public List<Vertex> outEdges(Vertex source) {

List<Vertex> outEdges = new ArrayList<Vertex>();

if (targets != null) {
}

return outEdges;
}

// Returns a list of incoming edges to the given vertex.
public List<Vertex> inEdges(Vertex target) {
List<Vertex> inEdges = new ArrayList<Vertex>();

for (Vertex source : adj.keySet()) {
}
}

return inEdges;
}

@Override
public String toString() {
}

//Returns the last (top-most/most recent) navigatable vertex on the stack, or none if
// there are no vertices available.
public Vertex getLastAvailOnStack(Vertex currentVertex, Deque<Vertex> stack) {
Iterator<Vertex> it = stack.descendingIterator();

while (it.hasNext()) {
Vertex next = it.next();
if (hasEdge(currentVertex, next)) {
return next;
}
}

return null;
}

//Traverses each edge in each direction once.
//It ends by printing the edges remaining to be seen (not optimal),
// and returns the path that it took.
public static <Vertex> List<Vertex> visitEachEdgeTwice(Graph<Vertex> graph, Vertex startVertex) {

//So we can prioritize unseen vertices over backtracking.
Deque<Vertex> stack = new ArrayDeque<Vertex>();

//To keep track of which vertices have been traversed.
graph = new Graph<Vertex>(graph);

stack.push(startVertex);

Vertex currentVertex = startVertex;

while (!stack.isEmpty()) {
Vertex  nextVisitable = null;

for (Vertex target : graph.outEdges(currentVertex)) {
if (graph.hasEdge(currentVertex, target)) {
if (!stack.contains(target)) {
nextVisitable = target;
}
}

}

//Backtrack if we don't have any other choice.
//We're going to pick the neighboring vertex that is farthest away
// from our "root" (bottom of stack).
if (nextVisitable == null) {
nextVisitable = graph.getLastAvailOnStack(currentVertex, stack);
}

//If we have a next node, traverse the edge to it, removing it from
// the graph.
if (nextVisitable != null) {
graph.removeDirectedEdge(currentVertex, nextVisitable);

currentVertex = nextVisitable;

} else {
stack.pop();
}
}

//Poor form, but it would be awkward to return with the path, and we
// need to see the graph to ensure all the edges were traversed.
System.out.println(graph);

return path;
}

public static void main(String[] args) {
Graph<Character> g = new Graph<Character>();

// The edgeless graph from the question:
List<Character> vertices = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P');

// There's some edge duplication here, but I'd rather be doubly sure
// I'm representing every edge than to accidentally forget one.
// They won't be duplicated in the graph itself.

List<Character> path = visitEachEdgeTwice(g, 'B');

System.out.println(path);
}
}

• To solve the last problem, I think I'm just going to abandon the idea of copying the Graph inside the method. If the caller doesn't want their graph messed with, they can pass in a copy. – Carcigenicate Jul 6 '15 at 2:07
• Also, you can ignore the two ifs: if (nextVisitable == null) { and the one after it that can be combined into a if...else. I should have caught that before posting, but I can't change it now. – Carcigenicate Jul 6 '15 at 2:15
• You should review what is an Eulerian Tour first. After that the solution becomes way too easy. – Dietr1ch Jul 6 '15 at 4:36
• I'm assuming that we should treat this as a homework question. – 200_success Jul 6 '15 at 5:50
• @200_success Yes. Sorry, I thought the first paragraph made that clear. – Carcigenicate Jul 6 '15 at 10:53

### Refer to types by interface instead of implementation

HashMap<Vertex, HashSet<Vertex>> adj = new HashMap<Vertex, HashSet<Vertex>>();


This is preferable:

Map<Vertex, Set<Vertex>> adj = new HashMap<Vertex, Set<Vertex>>();


### Make fields final when possible

The member variable adj is never reassigned, therefore it can be final.

### Validate first before other operations

In addDirectedToVertex, you first add target to the graph if it's not there yet, and then check if source is valid or not, otherwise throw exception. It would be letter to change the order of operations, do the validation first.

### Simplify hasEdge

The if-else can be simplified with a ternary:

return targets != null && targets.contains(target)


### Inconsistent handling of invalid parameters

In outEdges, if the specified source doesn't exist, you return an empty list. But such source is effectively invalid, and many of your other methods throw an exception in such situations. It would be good to be consistent and so likewise here.

It's also not great to give a variable the same name as that of a method.

### Using a POD class vs printing

Using a POD class is clearly the lesser evil. Don't use printing to verify "with your eyes".

• Thank you. For cases like hasEdge and addDirectedEdgd, in case the user passes in an "unknown" vertex, would your say it's more appropriate to throw, or ignore? – Carcigenicate Jul 6 '15 at 10:51
• And I thought once you declare another constructor, Java no longer supplies a default constructor. I don't have my IDE in front of me to test this though. Is this not the case? – Carcigenicate Jul 6 '15 at 10:52
• You're right about the default constructor, I overlooked the place where you use it, so yes, you still need it, I removed that from my post. – janos Jul 6 '15 at 11:28
• I'm not sure what is an "unknown" vertex. If such parameter doesn't make sense, then it's better to throw, to alert the programmer. Doing nothing can be more harmful, causing confusing or unpredictable behavior later, when it will be harder to understand and debug. – janos Jul 6 '15 at 11:30
• By "unknown vertex", I mean, say the Graph consists of vertical labelled a-f, and someone wants to check for an edge between a and Z (Z doesn't exist). Should I throw, or ignore that and just return false? I don't want to hide any potential errors (like the fact that someone is looking for a vertex that doesn't exist), but I don't want to throw if it's overkill and unnecessary. – Carcigenicate Jul 6 '15 at 11:35