-
-
Notifications
You must be signed in to change notification settings - Fork 50.1k
added TSP solution using MST implementation with docstrings under Graphs #13682
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
d3d010f
831a50b
1452f5d
c1b0edd
038739f
1dffc2c
c5c777a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| import heapq | ||
|
|
||
|
|
||
| def tsp(cost): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: |
||
| """ | ||
| https://www.geeksforgeeks.org/dsa/approximate-solution-for-travelling-salesman-problem-using-mst/ | ||
|
|
||
| Problem definition: | ||
| Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. | ||
| The task is to complete a tour from city 0 to all other towns such that we visit each city exactly once | ||
| and then return to city 0 at minimum cost. | ||
|
|
||
| Both the Naive and Dynamic Programming solutions for this problem are infeasible. | ||
| In fact, there is no polynomial time solution available for this problem as it is a known NP-Hard problem. | ||
|
|
||
| There are approximate algorithms to solve the problem though; for example, the Minimum Spanning Tree (MST) based | ||
| approximation algorithm defined below which gives a solution that is at most twice the cost of the optimal solution. | ||
|
|
||
| Assumptions: | ||
| 1. The graph is complete. | ||
|
|
||
| 2. The problem instance satisfies Triangle-Inequality.(The least distant path to reach a vertex j from i is always to reach j | ||
| directly from i, rather than through some other vertex k) | ||
|
|
||
| 3. The cost matrix is symmetric, i.e., cost[i][j] = cost[j][i] | ||
|
|
||
| Time complexity: O(n ^ 3), the time complexity of triangleInequality() function is O(n ^ 3) as we are using 3 nested loops. | ||
| Space Complexity: O(n ^ 2), to store the adjacency list, and creating MST. | ||
|
|
||
| """ | ||
| # create the adjacency list | ||
| adj = create_list(cost) | ||
|
|
||
| # check for triangle inequality violations | ||
| if triangle_inequality(adj): | ||
| print("Triangle Inequality Violation") | ||
| return -1 | ||
|
|
||
| # construct the travelling salesman tour | ||
| tsp_tour = approximate_tsp(adj) | ||
|
|
||
| # calculate the cost of the tour | ||
| tsp_cost = tour_cost(tsp_tour) | ||
|
|
||
| return tsp_cost | ||
|
|
||
|
|
||
| # function to implement approximate TSP | ||
| def approximate_tsp(adj): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: |
||
| n = len(adj) | ||
|
|
||
| # to store the cost of minimum spanning tree | ||
| mst_cost = [0] | ||
|
|
||
| # stores edges of minimum spanning tree | ||
| mst_edges = find_mst(adj, mst_cost) | ||
|
|
||
| # to mark the visited nodes | ||
| visited = [False] * n | ||
|
|
||
| # create adjacency list for mst | ||
| mst_adj = [[] for _ in range(n)] | ||
| mst_edges = find_mst(adj, mst_cost) | ||
| for e in mst_edges: | ||
| mst_adj[e[0]].append([e[1], e[2]]) | ||
| mst_adj[e[1]].append([e[0], e[2]]) | ||
|
|
||
| # to store the eulerian tour | ||
| tour = [] | ||
| eulerian_circuit(mst_adj, 0, tour, visited, -1) | ||
|
|
||
| # add the starting node to the tour | ||
| tour.append(0) | ||
|
|
||
| # to store the final tour path | ||
| tour_path = [] | ||
|
|
||
| for i in range(len(tour) - 1): | ||
| u = tour[i] | ||
| v = tour[i + 1] | ||
| weight = 0 | ||
|
|
||
| # find the weight of the edge u -> v | ||
| for neighbor in adj[u]: | ||
| if neighbor[0] == v: | ||
| weight = neighbor[1] | ||
| break | ||
|
|
||
| # add the edge to the tour path | ||
| tour_path.append([u, v, weight]) | ||
|
|
||
| return tour_path | ||
|
|
||
|
|
||
| def tour_cost(tour): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: |
||
| cost = 0 | ||
| for edge in tour: | ||
| cost += edge[2] | ||
| return cost | ||
|
|
||
|
|
||
| def eulerian_circuit(adj, u, tour, visited, parent): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: Please provide descriptive name for the parameter: Please provide type hint for the parameter: Please provide type hint for the parameter: Please provide type hint for the parameter: Please provide type hint for the parameter: |
||
| visited[u] = True | ||
| tour.append(u) | ||
|
|
||
| for neighbor in adj[u]: | ||
| v = neighbor[0] | ||
| if v == parent: | ||
| continue | ||
|
|
||
| if visited[v] == False: | ||
| eulerian_circuit(adj, v, tour, visited, u) | ||
|
|
||
|
|
||
| # function to find the minimum spanning tree | ||
| def find_mst(adj, mst_cost): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: Please provide type hint for the parameter: |
||
| n = len(adj) | ||
|
|
||
| # to marks the visited nodes | ||
| visited = [False] * n | ||
|
|
||
| # stores edges of minimum spanning tree | ||
| mst_edges = [] | ||
|
|
||
| pq = [] | ||
| heapq.heappush(pq, [0, 0, -1]) | ||
|
|
||
| while pq: | ||
| current = heapq.heappop(pq) | ||
|
|
||
| u = current[1] | ||
| weight = current[0] | ||
| parent = current[2] | ||
|
|
||
| if visited[u]: | ||
| continue | ||
|
|
||
| mst_cost[0] += weight | ||
| visited[u] = True | ||
|
|
||
| if parent != -1: | ||
| mst_edges.append([u, parent, weight]) | ||
|
|
||
| for neighbor in adj[u]: | ||
| v = neighbor[0] | ||
| if v == parent: | ||
| continue | ||
| w = neighbor[1] | ||
|
|
||
| if not visited[v]: | ||
| heapq.heappush(pq, [w, v, u]) | ||
| return mst_edges | ||
|
|
||
|
|
||
| # function to calculate if the | ||
| # triangle inequality is violated | ||
| def triangle_inequality(adj): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: |
||
| n = len(adj) | ||
|
|
||
| # Sort each adjacency list based | ||
| # on the weight of the edges | ||
| for i in range(n): | ||
| adj[i].sort(key=lambda a: a[1]) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide descriptive name for the parameter: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please provide descriptive name for the parameter: |
||
|
|
||
| # check triangle inequality for each | ||
| # triplet of nodes (u, v, w) | ||
| for u in range(n): | ||
| for x in adj[u]: | ||
| v = x[0] | ||
| cost_UV = x[1] | ||
raisaaajose marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| for y in adj[v]: | ||
| w = y[0] | ||
| cost_VW = y[1] | ||
raisaaajose marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| for z in adj[u]: | ||
| if z[0] == w: | ||
| cost_UW = z[1] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Variable and function names should follow the |
||
| if (cost_UV + cost_VW < cost_UW) and (u < w): | ||
| return True | ||
| # no violations found | ||
| return False | ||
|
|
||
|
|
||
| # function to create the adjacency list | ||
| def create_list(cost): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file Please provide return type hint for the function: Please provide type hint for the parameter: |
||
| n = len(cost) | ||
|
|
||
| # to store the adjacency list | ||
| adj = [[] for _ in range(n)] | ||
|
|
||
| for u in range(n): | ||
| for v in range(n): | ||
| # if there is no edge between u and v | ||
| if cost[u][v] == 0: | ||
| continue | ||
| # add the edge to the adjacency list | ||
| adj[u].append([v, cost[u][v]]) | ||
|
|
||
| return adj | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # test | ||
| cost = [[0, 1000, 5000], [5000, 0, 1000], [1000, 5000, 0]] | ||
|
|
||
| print(tsp(cost)) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
graphs/travelling_salesman.py, please provide doctest for the functiontspPlease provide return type hint for the function:
tsp. If the function does not return a value, please provide the type hint as:def function() -> None:Please provide type hint for the parameter:
cost