I'm trying to make a Java implementation for the Traveling Salesman Problem. I have read a lot about the different optimal algorithms and I found that the Held-Karp algorithm is a good one to implement. Now my problem is that I'm trying to make an adjacency matrix to store my edge values and then use these values to implement the algorithm and I cannot find a good logic to make the adjacency matrix.
My code reads from a file(graphFile) which has edges and their associated cost. The file is as follows:
A : B : 10
A : C : 3
A : D : 30
etc
Now my code reads the file, goes through each line and stores the vertices(nodes) in a SortedSet in the form of [A, B, C, D, ...]. Meanwhile, the edges are stored in a TreeMap along with their associated cost in the form of {AB = 10, AC = 3, ...}. I use my vertices set to define the size of my adjacency matrix and that is where I get stuck.
What would be the bet way on inserting the associated values of my edges in my adjacency matrix? Is that even a good way to solve the TSP or I'm on the wrong track?
static int[][] adjacencyMatrix;
static SortedSet<String> vertices = new TreeSet<String>();
static TreeMap<String, Integer> edgeCost = new TreeMap<String, Integer>();
Here is a code snippet that should help. This piece of code reads the file and stores the values accordingly in the Map and Set:
while (graphFile.hasNextLine()) {
line = graphFile.nextLine();
tokenizer = line.split(" : ");
try {
if (tokenizer.length != 3) {
continue;
}
String source = tokenizer[0];
String dest = tokenizer[1];
String cost = tokenizer[2];
addVertex(source, dest); //Add Vertex to set of vertices. Duplicates are removed.
addEdge(source+dest, Integer.parseInt(cost)); //Add edges to an array then add array to list of edges.
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Wrongly Formatted Line " + line);
}
}
Now I have a code that computes my adjacencyMatrix. So far I managed to only make the diagonal part of the matrix(with value INF = 99999). However I have a logic problem of how to store the rest of the edgeCost values in the matrix.
private static void createAdjacencyMatrix() {
for(int i=0; i<adjacencyMatrix.length; i++){
for(int j=0; j<adjacencyMatrix.length; j++){
if(i == j){
adjacencyMatrix[i][j] = INF;
}
}
}
//Part where values of edgeCost should be added in matrix. Logic problem here.
}
}
Now I was thinking of, instead of making an adjacency matrix, I use an adjacency list. Which one would be better for the TSP using the Held-Karp algorithm?