What I want to do:
I am trying to implement the Travelling Salesman Problem using a weighted directed graph. That means that I will need to visit different vertices, but I can't figure out how to get the vertices using JGraphT.
I want to do something like:
getVertex(Chicago);
for (edges coected to chicagoVertex)
pick the one with the smallest weight
Problem/What I've tried:
But I can't figure out how to do the getVertex(x) part. JGraphT has a getEdge(), but there's not a getVertex() method. I read here about picking a random vertex with vertexSet(), but I don't understand how it works. It is just creating a vertex and storing it in an object array, but if I use that, that means every time I look for a vertex, I need to traverse the entire array searching for the vertex value (which seems very inefficient).
Question:
Does anyone know a way that I can grab a vertex using JGraphT where I can do something like getVertex? If not, is there another more efficient way to get a vertex rather than iterating over an array each time I need to find the next node to visit?
Code:
I don't know if it might help, but here is the setup I have right now: import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleDirectedWeightedGraph;
/**
*
*
*/
public class TravellingSalesman {
private static final SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> cities =
new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
public static void main(String [] args){
createGraph();
}
/**
*
*/
private static void createGraph(){
//Vertices
cities.addVertex("Chicago");
cities.addVertex("Los Angeles");
cities.addVertex("New York");
//Edges
DefaultWeightedEdge e1 = (DefaultWeightedEdge) cities.addEdge("Los Angeles", "Chicago");
cities.setEdgeWeight(e1, 5);
DefaultWeightedEdge e2 = (DefaultWeightedEdge)cities.addEdge("Chicago", "New York");
cities.setEdgeWeight(e2, 3);
DefaultWeightedEdge e3 = (DefaultWeightedEdge)cities.addEdge("New York", "Los Angeles");
cities.setEdgeWeight(e3, 8);
}
private static void tsp(){
int [] checked = new int[3];
//STEP 1: Start at an arbitrary index
//STEP 2: Find the shortest edge coecting the current one and an unvisited vertex
//STEP 3: Travel to the unvisited vertex
//STEP 4: Mark the "unvisited" vertex as the current index
//STEP 5: Mark the current as visited
//STEP 6: If all vertices are visited, stop the program
}
}
Note: This is not homework. Just trying to build my graphing skills.
