You need to have the following method: Build the graph:The graph should contain all of the vertices
Question:
You need to have the following method:
- Build the graph:The graph should contain all of the vertices and edges that connect them.
- TSP:The TSP method should be created using dynamic programming. The output of this method shows all of the nodes that are visited.
Submit a zip file that contains the following:
- Output screenshot
- Program source code
Sol77:
To build the graph, you can use an adjacency matrix or an adjacency list. For the given image, you can create a matrix with 6 rows and 6 columns to represent the weights between each pair of vertices. For example, the weight between vertex 1 and vertex 2 is 3, so you can set matrix[1][2] = 3 and matrix[2][1] = 3.
To implement the TSP using dynamic programming, you can use the Held-Karp algorithm. The basic idea is to calculate the shortest path between all pairs of vertices and then use these calculations to determine the shortest path for the entire graph. You can start with a subset of vertices, and then add one more vertex at a time until you have visited all of them.
Here's some pseudo code for the TSP using dynamic programming:
- Create a matrix D with dimensions (2^n) x n, where n is the number of vertices
- For each subset S of vertices with size 1, set D[S][v] = weight of edge from vertex 0 to vertex v
- For each subset S of vertices with size > 1 and containing vertex 0: a. For each vertex v in S: i. Let S' be the subset of vertices in S except v ii. Set D[S][v] = min(D[S'][u] + weight of edge from vertex u to vertex v), where u is any vertex in S' except v
- Let S be the set of all vertices
- Let p be the vertex in S other than 0 that minimizes D[S][p] + weight of edge from vertex p to vertex 0
- Let tour be the sequence of vertices obtained by starting at 0, following the path in D[S][p] to p, and then following the edge from p to 0
- Return tour
You can then print the nodes in the order of the tour to get the output.